Diviser le tableau d'objets par année JSON à l'aide de PHP
P粉924915787
P粉924915787 2024-02-03 22:31:37
0
2
304

Ma question est de savoir comment obtenir ou diviser un tableau par ordre croissant en utilisant la date clé du tableau,

J'ai beaucoup essayé... mais je n'ai pas réussi,

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

Le résultat dont j'ai besoin est :

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

Comment faire cela en utilisant PHP ou JavaScript ?

P粉924915787
P粉924915787

répondre à tous(2)
P粉512363233

La version PHP pourrait ressembler à ceci :

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

Comme demandé dans la réponse de Diego, j'y ai également mis ksort, qui trie le tableau résultant par ordre décroissant par clé.

P粉726133917

Voici une démo sur la façon de convertir un tableau d'entrée en un objet de sortie attendu à l'aide de 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 );
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!