[英]Sort array using PHP - group by key value
I grab data by running a cURL operation and then use:我通过运行 cURL 操作来获取数据,然后使用:
<?php
$data = json_decode($result, true);
print_r($data)
?>
to output:输出:
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
)
)
Is it possible to group my results by date ?是否可以按日期对我的结果进行分组?
I can display my results like this:我可以像这样显示我的结果:
<?php
foreach($data as $entry){
echo $entry['id'];
}
?>
However, I'd like to group my results by $entry['date']
但是,我想按
$entry['date']
结果进行分组
How do I achieve this?我如何实现这一目标?
uasort($data, function($a, $b) {
return strtotime($a['date']) > strtotime($b['date']);
});
The following will sort the array by date in ascending order.以下将按日期按升序对数组进行排序。
usort($data, function ($x,$y) {
return strtotime($x['date']) - strtotime($y['date']);
});
_Edit: I may have misunderstood the question so if the intent is to retrieve only the dates in a separate array then perform the following: _Edit:我可能误解了这个问题,所以如果目的是仅检索单独数组中的日期,则执行以下操作:
$dates = array_column($data, 'date');
If you needed the dates sorted after this then perform the usort
example above by passing the $dates
array as follows:如果您需要在此之后排序的日期,则通过传递
$dates
数组来执行上面的usort
示例,如下所示:
usort($dates, function ($x,$y) {
return strtotime($x) - strtotime($y);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.