Split array of objects by JSON year using PHP
P粉924915787
P粉924915787 2024-02-03 22:31:37
0
2
368

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粉924915787
P粉924915787

reply all(2)
P粉512363233

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.

P粉726133917

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 );
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template