我的问题是如何使用数组键日期按升序获取或拆分数组,
我尝试了很多...但我没有得到它,
[
{
"id": "47",
"date": "07/16/2022",
"text": "ph"
}
{
"id": "46",
"date": "06/16/2022",
"text": "ph"
},
{
"id": "45",
"date": "06/16/2021",
"text": "ph"
}]
我需要的输出是,
[
"2021": [{
"id": "45",
"date": "06/16/2021",
"text": "ph"
}],
"2022": [{
"id": "46",
"date": "06/16/2022",
"text": "ph"
},
{
"id": "47",
"date": "07/16/2022",
"text": "ip"
}]
]
如何使用 PHP 或 JavaScript 来完成此操作?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP 版本可能如下所示:
$input = [ [ "id" => "47", "date" => "07/16/2022", "text" => "ph" ], [ "id" => "46", "date" => "06/16/2022", "text" => "ph" ], [ "id" => "45", "date" => "06/16/2021", "text" => "ph" ] ]; $result = []; foreach ($input as $entry) { $date = new DateTime($entry['date']); $result[$date->format('Y')][] = $entry; } ksort($result);正如迭戈的回答所问,我也将
ksort放入其中,它按键按降序对结果数组进行排序。这是一个关于如何使用 JavaScript 将输入数组转换为预期输出对象的演示:
const input = [ { "id": "47", "date": "07/16/2022", "text": "ph" }, { "id": "46", "date": "06/16/2022", "text": "ph" }, { "id": "45", "date": "06/16/2021", "text": "ph" } ]; const output = {}; //for each object in the input array for(o of input){ //parse the year part of the date property const year = o.date.substring(6); //if the parsed year doesn't exist yet in the output object if (!output.hasOwnProperty(year)) //then add an empty array to the year key in the output object output[year] = []; //add the current input object to the array bound to the year key in the output object output[year].push(o); } console.log( output );