1

我需要一些关于对多个数组进行排序的帮助。这就是我得到的:

Array ( 
   [ALU0000001] => 
         Array ( [0] => Array ( [period] => 2012 [codCurse] => S12-2030 [idPersona] => ALU0000001 [date] => 2012-04-02 [amount] => 238.00 [active] => X ) 
                 [1] => Array ( [period] => 2012 [codCurse] => S12-2030 [idPersona] => ALU0000001 [date] => 2012-05-02 [amount] => 238.00 [active] => X )
                 [2] => Array ( [period] => 2012 [codCurso] => S12-2030 [idPersona] => ALU0000001 [date] => 2012-06-02 [amount] => 238.00 [active] => X )
                 [3] => Array ( [period] => 2013 [codCurso] => S12-2030 [idPersona] => ALU0000001 [date] => 2013-01-02 [amount] => 238.00 [active] => X )

   [ALU0000005] =>
         Array ( [0] => Array ( [period] => 2013 [codCurse] => S13-2010 [idPersona] => ALU0000005 [date] => 2013-03-01 [amount] => 225.00 [active] => X )
                 [1] => Array ( [period] => 2013 [codCurse] => S13-2010 [idPersona] => ALU0000005 [date] => 2013-03-02 [amount] => 333.00 [active] => X ) 
                 [2] => Array ( [period] => 2013 [codCurse] => S13-2010 [idPersona] => ALU0000005 [date] => 2013-04-02 [amount] => 333.00 [active] => X ) 

我需要按期间日期对多数组进行排序以获得类似的东西

  Y   M   D
  2012 2012-04-02 ALU00000001 .....
  2012 2012-05-02 ALU00000005 .....
  2012 2012-06-01 ALU00000001 .....
  2013 2013-01-01 ALU00000001 .....
  2013 2013-06-01 ALU00000001 .....
  2013 2013-12-24 ALU00000005 .....

谢谢

4

2 回答 2

1

正如 danp 所说,您将需要使用PHP usort的自定义排序功能。

您可以使用语法在 Codeigniter 中执行此操作;

usort($data_array, array('controller', 'sort_function'));

function sort_function($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
于 2013-01-08T13:43:48.757 回答
0

考虑到主数组键的作用不大(因为它们已经包含在date键的值中),您可以放心地忽略它们。因此,首先您要将所有值收集到一个数组中以便以后进行排序:

$allItems = array();
foreach ($outputArr as $arr) { // $outputArr should be the name of your array
    $allItems = array_merge($allItems,array_values($arr));
}

然后您需要date按键对数组值进行排序:

function sortByDate($a,$b) {
    $d1 = strtotime($a['date']);
    $d2 = strtotime($b['date']);
    return $d1 == $d2 ? 0 : ($d1 > $d2 ? 1 : -1);
}
usort($allItems,'sortByDate');
// and there you go.
print_r($allItems);
于 2013-01-08T13:59:25.390 回答