首頁  >  問答  >  主體

使用 PHP 依 JSON 年份拆分數組的對象

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

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

[
{
    "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粉924915787P粉924915787233 天前310

全部回覆(2)我來回復

  • P粉512363233

    P粉5123632332024-02-04 20:18:04

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

    回覆
    0
  • P粉726133917

    P粉7261339172024-02-04 14:04:49

    這是一個關於如何使用 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 );

    回覆
    0
  • 取消回覆