简体   繁体   中英

PHP Sorting Inner, Inner Array

Okay I have an array like this:

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"
                      }
    }
}

Now what I want to do is sort the inner inner array (the one with the time values) by the time values. Just so that inner array is sorted by the time values. How would I do this?

I do have PHP 5.3 installed if that is helpful.

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

Try this:

$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
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

I don't think it gets any simpler to sort the second level -- iterate the first level and call sort() on each occurrence. Because your string are presumably hh:ii:ss , it is completely safe to compare them as simple strings (no need to strtotime() ).

Code: ( 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);

Output:

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',
    ),
  ),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM