Heim  >  Fragen und Antworten  >  Hauptteil

Teilen Sie das Array von Objekten mithilfe von PHP nach JSON-Jahr auf

Meine Frage ist, wie man ein Array mithilfe des Array-Schlüsseldatums in aufsteigender Reihenfolge erhält oder aufteilt,

Ich habe viel versucht...aber ich habe es nicht geschafft,

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

Die Ausgabe, die ich brauche, ist

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

Wie geht das mit PHP oder JavaScript?

P粉924915787P粉924915787233 Tage vor306

Antworte allen(2)Ich werde antworten

  • 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 放入其中,它按键按降序对结果数组进行排序。

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

    Antwort
    0
  • StornierenAntwort