2017-07-07 279 views
-1

数组键是日期并且想按排列顺序按日期排列数组。以下是阵列:按日期排序数组php

Array 
(
    [07/14/2017] => Array 
     (
      [ID] => 5442 
      [post_content] => Test1 
      [post_title] => Testevents1 
     ) 

    [01/11/2017] => Array 
     (
      [ID] => 5443 
      [post_content] => Test2 
      [post_title] => Testevents2 
     ) 
) 
+0

其已经回答[这里](https://开头stackoverflow.com/questions/38770210/how-to-sort-array-with-date-as-key)与更多解释[这里](https://stackoverflow.com/questions/17364127/how-can-i-sort -arrays-and-data-in-php) –

+0

这是你的答案[answer](https://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array包含日期的元素) –

回答

2

数组中的键可以使用uksort做到这一点:

uksort($arr, function ($a, $b) { 
    $t1 = strtotime($a); 
    $t2 = strtotime($b); 
    if ($t1 == $t2) { 
     return 0; 
    } 
    return ($t1 > $t2) ? 1 : -1; 
}); 
+0

如何循环即多个记录 –

+0

@RDMage多个记录的外观如何? “for”还是“foreach”适合你的情况? –

+0

ksort($ new)在foreach中工作正常,谢谢 –

0

您可以使用uksort

uksort - 按使用用户自定义的比较函数

function cmp($keyA, $keyB) 
{ 
    // Your date parsing and comparison 

    // The comparison function must return an integer less than, equal to, 
    // or greater than zero if the first argument is considered to be respectively 
    // less than, equal to, or greater than the second. 
    // Note that before PHP 7.0.0 this integer had to be in the range 
    // from -2147483648 to 2147483647. 
} 

uksort($arr, "cmp") 
+0

如何循环即多个记录 –