PHP排序内部,内部数组

时间:2012-11-20 21:50:33

标签: php arrays sorting

好的,我有一个这样的数组:

array {
    [0] => array {
               [0] => array {
                         ["Time"] => "01:00:00"
                      }
               [1] => array {
                         ["Time"] => "00:00:00"
                      }
    }
    [1] => array {
               [0] => array {
                         ["Time"] => "01:00:00"
                      }
               [1] => array {
                         ["Time"] => "00:00:00"
                      }
    }
}

现在我要做的是按时间值对内部内部数组(具有时间值的数组)进行排序。只是为了使内部数组按时间值排序。我该怎么做?

如果有帮助,我确实安装了PHP 5.3。

4 个答案:

答案 0 :(得分:2)

foreach ( $array as $key => &$part )
{
    usort( &$part, function( $a, $b ) {
        return strtotime($a['Time'])-strtotime($b['Time']) > 0;
    });
}

答案 1 :(得分:1)

试试这个:

$arr = array(array(array("Time" => "01:00:00"), array("Time" => "02:00:00"), array("Time" => "00:00:00")),
             array(array("Time" => "02:00:00"), array("Time" => "01:00:00"), array("Time" => "00:00:00")));

$c = count($arr);
for ($i = 0; $i < $c; $i++) {
    sort($arr[$i]);
}

var_dump($arr); // outputs desired array

答案 2 :(得分:0)

function custom_map( $array ) {
    usort( $array, function( $a, $b ) {
        return strtotime($a['Time'])-strtotime($b['Time']) > 0;
    });
    return $array;
}

$new_array = array_map( "custom_map", $array );

http://se1.php.net/manual/en/function.usort.php

http://se1.php.net/manual/en/function.array-map.php

答案 3 :(得分:0)

我认为对第二级进行排序没有任何简单的方法-迭代第一级并在每次出现时调用sort()。因为您的字符串大概是hh:ii:ss,所以将它们作为简单字符串进行比较是完全安全的(不需要strtotime())。

代码:(Demo

$array = [
    [
        ['Time' => "01:00:00"],
        ['Time' => "00:00:00"]
    ],
    [
        ['Time' => "01:00:00"],
        ['Time' => "00:00:00"]
    ]
];

array_walk($array, 'sort');
var_export($array);

输出:

array (
  0 => 
  array (
    0 => 
    array (
      'Time' => '00:00:00',
    ),
    1 => 
    array (
      'Time' => '01:00:00',
    ),
  ),
  1 => 
  array (
    0 => 
    array (
      'Time' => '01:00:00',
    ),
    1 => 
    array (
      'Time' => '00:00:00',
    ),
  ),
)