[英]How to sort a 3 dimensional array by element containing date, from newest to oldest
我有一個 3 維數組,其結構如下所示。 為了清楚起見,我們將最里面的 arrays 稱為記錄。 我需要對最外層的數組進行排序,使其從最新到最舊進行排序。
Array (
[0] => Array (
[0] => Array (
[personNum] => 2
[type] => comment
[datetime] => 2019-05-15 11:29:45
),
[1] => Array (
[personNum] => 3
[type] => status
[datetime] => 2019-05-26 15:59:53
)
),
[1] => Array (
[0] => Array (
[personNum] => 3
[type] => status
[datetime] => 2019-05-26 15:59:53
)
[1] => Array (
[personNum] => 4
[type] => status
[datetime] => 2019-05-26 16:04:24
)
)
)
I have checked this and this links, and I know that custom functions is the way to go, and i am trying to understand it for 2D arrays but i am not getting a hang of how it would work for 3D arrays.
您可以嘗試使用 usort:
使用用戶定義的比較按值對數組進行排序 function https://www.php.net/manual/en/function.usort.php
usort($allArray,function($a,$b){
return $a[0]['dateTime']-$b[0]['dateTime'];
})
您可以將其作為一個兩階段過程來執行。 首先,使用array_walk
和array_multisort
按datetime
對內部 arrays 進行排序。 然后使用usort
,比較內部 arrays 的最大datetime
時間值:
array_walk($arr, function (&$v) { array_multisort(array_column($v, 'datetime'), SORT_DESC, $v); });
usort($arr, function ($a, $b) {
return strcmp(max(array_column($b, 'datetime')), max(array_column($a, 'datetime')));
});
print_r($arr);
Output:
Array
(
[0] => Array
(
[0] => Array
(
[personNum] => 4
[type] => status
[datetime] => 2019-05-26 16:04:24
)
[1] => Array
(
[personNum] => 3
[type] => status
[datetime] => 2019-05-26 15:59:53
)
)
[1] => Array
(
[0] => Array
(
[personNum] => 3
[type] => status
[datetime] => 2019-05-26 15:59:53
)
[1] => Array
(
[personNum] => 2
[type] => comment
[datetime] => 2019-05-15 11:29:45
)
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.