Sort Multi Array in PHP

后端 未结 9 1906
清酒与你
清酒与你 2021-01-23 07:10

Does anybody have an idea how can I sort this array by key (date) in PHP?

Array
(   
    [2011-02-16] => Array
        (
            [date] => 2011-02-16
          


        
相关标签:
9条回答
  • 2021-01-23 08:05

    http://www.php.net/manual/en/function.array-multisort.php

    Would example #3 suit your needs?

    0 讨论(0)
  • 2021-01-23 08:09

    A better answer would be to use uksort which is used to sort keys with a user-defined function (considering that these dates cannot always be compared and cannot be sorted with ksort without first applying strtotime to the keys):

    function sort_by_date_keys($date_key1, $date_key2) {
        // reverse the order of the $date_keys for "oldest to newest"
        return strtotime($date_key2) - strtotime($date_key1);
    );
    
    uksort($array, 'sort_by_date_keys');
    

    This method is more defined than uasort as it was tailored for keys.

    Example:

    $array = array(
        '1/1/12' => 'foo1',
        '1/1/13' => 'foo2'
    );
    uksort($array, 'sort_by_date_keys');
    
    // output
    $array = array(
        '1/1/13' => 'foo2',
        '1/1/12' => 'foo1'
    );
    
    0 讨论(0)
  • 2021-01-23 08:11

    Since your array already has the date in the keys, why not just use ksort? The string comparison should work fine since you're using YYYY-MM-dd format.

    0 讨论(0)
提交回复
热议问题