Rumah > Soal Jawab > teks badan
Soalan saya ialah bagaimana untuk mendapatkan atau membahagi tatasusunan dalam tertib menaik menggunakan tarikh kunci tatasusunan,
Saya dah cuba banyak...tapi tak dapat,
[ { "id": "47", "date": "07/16/2022", "text": "ph" } { "id": "46", "date": "06/16/2022", "text": "ph" }, { "id": "45", "date": "06/16/2021", "text": "ph" }]
Output yang saya perlukan ialah,
[ "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" }] ]
Bagaimana untuk melakukan ini menggunakan PHP atau JavaScript?
P粉5123632332024-02-04 20:18:04
Versi PHP mungkin kelihatan seperti ini:
$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);
Seperti yang ditanya dalam jawapan Diego, saya juga meletakkan ksort
di dalamnya, yang menyusun tatasusunan yang terhasil dalam tertib menurun mengikut kekunci.
P粉7261339172024-02-04 14:04:49
Berikut ialah demo tentang cara menukar tatasusunan input kepada objek keluaran yang dijangka menggunakan 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 );