Sort Multi Array in PHP

后端 未结 9 2003
清酒与你
清酒与你 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条回答
  •  Happy的楠姐
    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'
    );
    

提交回复
热议问题