PHP Sort a multidimensional array by element containing date

后端 未结 10 1734
野趣味
野趣味 2020-11-22 09:02

I have an array such as:

Array
(
[0] => Array
    (
        [id] => 2
        [type] => comment
        [text] => hey
        [datetime] => 20         


        
相关标签:
10条回答
  • 2020-11-22 09:55

    http://us2.php.net/manual/en/function.array-multisort.php see third example:

    <?php
    
    $data[] = array('volume' => 67, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 1);
    $data[] = array('volume' => 85, 'edition' => 6);
    $data[] = array('volume' => 98, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 6);
    $data[] = array('volume' => 67, 'edition' => 7);
    
    foreach ($data as $key => $row) {
        $volume[$key]  = $row['volume'];
        $edition[$key] = $row['edition'];
    }
    
    array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
    
    ?>
    

    fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.

    0 讨论(0)
  • 2020-11-22 10:01

    You can simply solve this problem using usort() with callback function. No need to write any custom function.

    $your_date_field_name = 'datetime';
    usort($your_given_array_name, function ($a, $b) use (&$your_date_field_name) {
        return strtotime($a[$your_date_field_name]) - strtotime($b[$your_date_field_name]);
    });
    
    0 讨论(0)
  • 2020-11-22 10:02

    This should work. I converted the date to unix time via strtotime.

      foreach ($originalArray as $key => $part) {
           $sort[$key] = strtotime($part['datetime']);
      }
      array_multisort($sort, SORT_DESC, $originalArray);
    

    One-liner version would be using multiple array methods:

    array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
                    SORT_DESC, 
                    $originalArray);
    
    0 讨论(0)
  • 2020-11-22 10:07

    For 'd/m/Y' dates:

    usort($array, function ($a, $b, $i = 'datetime') { 
        $t1 = strtotime(str_replace('/', '-', $a[$i]));
        $t2 = strtotime(str_replace('/', '-', $b[$i]));
    
        return $t1 > $t2;
    });
    

    where $i is the array index

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