Home  >  Q&A  >  body text

Split array of objects by JSON year using PHP

My question is how to get or split an array in ascending order using array key date,

I tried a lot...but I didn't get it,

[
{
    "id": "47",
    "date": "07/16/2022",
    "text": "ph"
}
{
    "id": "46",
    "date": "06/16/2022",
    "text": "ph"
},
{
    "id": "45",
    "date": "06/16/2021",
    "text": "ph"
}]

The output I need is,

[
"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"
}]
]

How to do this using PHP or JavaScript?

P粉924915787P粉924915787282 days ago359

reply all(2)I'll reply

  • P粉512363233

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

    The PHP version might look like this:

    $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);
    

    As asked in Diego's answer, I also put ksort in it, which sorts the resulting array in descending order by key.

    reply
    0
  • P粉726133917

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

    Here is a demonstration on how to use JavaScript to convert an input array into an expected output object:

    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 );

    reply
    0
  • Cancelreply