[英]Sort array using PHP - group by key value
我通過運行 cURL 操作來獲取數據,然后使用:
<?php
$data = json_decode($result, true);
print_r($data)
?>
輸出:
Array
(
[0] => Array
(
[id] => 258378365
[firstName] => Test
[lastName] => McTest
[phone] => 1235550101
[email] => test.mctest@example.com
[date] => January 10, 2019
)
[1] => Array
(
[id] => 253994842
[firstName] => Jane
[lastName] => McTest
[phone] => 1235550101
[email] => jane.mctest@example.com
[date] => December 13, 2018
)
[2] => Array
(
[id] => 253994843
[firstName] => Jane
[lastName] => McTest
[phone] => 1235550101
[email] => jane.mctest@example.com
[date] => January 10, 2019
)
)
是否可以按日期對我的結果進行分組?
我可以像這樣顯示我的結果:
<?php
foreach($data as $entry){
echo $entry['id'];
}
?>
但是,我想按$entry['date']
結果進行分組
我如何實現這一目標?
uasort($data, function($a, $b) {
return strtotime($a['date']) > strtotime($b['date']);
});
以下將按日期按升序對數組進行排序。
usort($data, function ($x,$y) {
return strtotime($x['date']) - strtotime($y['date']);
});
_Edit:我可能誤解了這個問題,所以如果目的是僅檢索單獨數組中的日期,則執行以下操作:
$dates = array_column($data, 'date');
如果您需要在此之后排序的日期,則通過傳遞$dates
數組來執行上面的usort
示例,如下所示:
usort($dates, function ($x,$y) {
return strtotime($x) - strtotime($y);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.