使用 PHP 依 JSON 年份拆分數組的對象
P粉924915787
P粉924915787 2024-02-03 22:31:37
0
2
309

我的問題是如何使用數組鍵日期按升序獲取或拆分數組,

我嘗試了很多...但我沒有得到它,

[
{
    "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 來完成此操作?

P粉924915787
P粉924915787

全部回覆(2)
P粉512363233

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 放入其中,它按鍵按降序對結果數組進行排序。

P粉726133917

這是一個關於如何使用 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 );
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!