使用uksort在PHP中对Month-Year多维数组进行排序

时间:2017-11-21 15:20:06

标签: php

我想对以下数组进行排序:

Array(
    [05/2017] => Array (
        [city] => 'ABC'
        [memebers] => '50'
    )
    [03/2017] => Array (
        [city] => 'ABC'
        [members] => '25'
    )
    [10/2016] => Array (
        [city] => 'ABC'
        [members] => '20'
    )
    [11/2017] => Array (
        [city] => 'ABC'
        [members] => '65'
    )
)

预期结果:

Array(
    [10/2016] => Array (
        [city] => 'ABC'
        [members] => '20'
    )
    [03/2017] => Array (
        [city] => 'ABC'
        [members] => '25'
    )
    [05/2017] => Array (
        [city] => 'ABC'
        [members] => '50'
    )
    [11/2017] => Array (
        [city] => 'ABC'
        [members] => '65'
    )
)

我使用uksort对其进行排序,但我猜uksort不适用于多维数组:

uksort($data, function($a1, $a2) {
    $time1 = strtotime($a1);
    $time2 = strtotime($a2);

    return $time1 - $time2;
});

请建议如何使用uksort或其他任何可能性?

1 个答案:

答案 0 :(得分:1)

这应该有效:

$data = 
    array(
        '05/2017' => array (
            'city' => 'ABC',
            'memebers' => '50'
        ),
        '03/2017' => array (
            'city' => 'ABC',
            'members' => '25'
        ),
        '10/2016' => array (
            'city' => 'ABC',
            'members' => '20'
        ),
        '11/2017' => array (
            'city' => 'ABC',
            'members' => '65'
        ),
    );

uksort($data, function($a1, $a2) {
    return DateTime::createFromFormat('m/Y|', $a1) <=> DateTime::createFromFormat('m/Y|', $a2);
});

var_dump($data);

您需要使用DateTime,因为您的日期格式不正确,然后只需比较时间戳。正如Mark指出的那样,使用&#34; m&#34;几个月,您可以使用&#34;&lt; =&gt;&#34;运算符(自PHP 7起)