我的問題是如何按年使用陣列鍵日期按升序獲取或拆分陣列,
試了很多次。。。還是沒搞定
[
{
"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 中做到這一點?
uj5u.com熱心網友回復:
這是一個關于如何使用 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 );
這與使用 php 實作的邏輯相同:
https://onlinephp.io/c/87510
<?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"
]
];
$output = [];
//for each object in the input array
foreach($input as $o){
//parse the year part of the date property
$year = substr($o['date'], 6);
//if the parsed year doesn't exist yet in the output object
if (!array_key_exists($year, $output))
//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][] = $o;
}
var_dump( $output );
uj5u.com熱心網友回復:
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);
正如 Diego 的回答所問的那樣,我也ksort加入了混合,它按鍵按降序對結果陣列進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491890.html
標籤:javascript php 数组 json
上一篇:正則運算式替換所有出現的文本,包括JavaScript中的括號
下一篇:在vue,js上設定動態css類
