如何通过startTime对数组进行排序?

时间:2016-10-21 10:08:28

标签: php arrays sorting

我如何通过startTime对此数组进行排序?

代码:

<Img src ='../../var/www/img.jpg' />

我正在动态地编写代码,我不想手动输入如下所示的密钥:

function arraySorter($a, $b) {
    return strtotime($a->startTime) - strtotime($b->startTime);
}   

usort($this->meetingSlotsTaken, 'arraySorter');

echo "<pre>";
    print_r($this->meetingSlotsTaken);
echo "</pre>";

打印出来:

usort($this->meetingSlotsTaken[0]['2016-10-07 14:10:00'], 'arraySorter');

2 个答案:

答案 0 :(得分:1)

您需要对数组中数组中的数组进行排序:

foreach($this->meetingSlotsTaken as $k1 => $v1){
    foreach($v1 as $k2 => $v2){
        usort($this->meetingSlotsTaken[$k1][$k2], 'arraySorter');
    }
}

答案 1 :(得分:0)

使用此示例:

$array = array(
    0 => array(
        'name' => 'Name0',
        'date' => '2016-10-10 15:30:00'
    ),
    1 => array(
        'name' => 'Name1',
        'date' => '2016-10-11 15:30:00'
    ),
    2 => array(
        'name' => 'Name3',
        'date' => '2016-10-13 15:30:00'
    ),
    3 => array(
        'name' => 'Name4',
        'date' => '2016-10-05 15:30:00'
    ),
    4 => array(
        'name' => 'Name5',
        'date' => '2016-10-09 15:30:00'
    )
);

$temp_array = array();
foreach ($array as $key => $value) {
    $temp_array[$key] = $value['date'];
}

asort($temp_array); // arsort() for reverse order

$output = array();
foreach ($temp_array as $key => $value) {
    $output[] = $array[$key];
}

echo "<pre>"; print_r($output);

结果:

Array
(
    [0] => Array
        (
            [name] => Name4
            [date] => 2016-10-05 15:30:00
        )

    [1] => Array
        (
            [name] => Name5
            [date] => 2016-10-09 15:30:00
        )

    [2] => Array
        (
            [name] => Name0
            [date] => 2016-10-10 15:30:00
        )

    [3] => Array
        (
            [name] => Name1
            [date] => 2016-10-11 15:30:00
        )

    [4] => Array
        (
            [name] => Name3
            [date] => 2016-10-13 15:30:00
        )

)