搜索

首页  >  问答  >  正文

使用 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粉924915787296 天前370

全部回复(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
  • 取消回复