如何合并两个多级PHP数组并按时间排序?
Got it, let's break down how to get your combined PSA API data sorted and ready for display—you're already halfway there with that standardized format!
Option 1: Use Timestamp Keys (Simple, Efficient)
Since you've formatted your data into an associative array where keys are timestamps ($formattedNotes[$noteTime] = [...]), merging and sorting is super straightforward:
Merge the two formatted arrays from your APIs:
// Assume you have two formatted arrays from each API $formattedNotesAPI1 = [...]; // Your first API's formatted data $formattedNotesAPI2 = [...]; // Your second API's formatted data $combinedNotes = array_merge($formattedNotesAPI1, $formattedNotesAPI2);Note: If two entries share the exact same timestamp,
array_mergewill overwrite the earlier entry with the later one. If you need to preserve all duplicates, jump to Option 2.Sort by timestamp
Useksort()to sort entries from oldest to newest (ascending order):ksort($combinedNotes);Or
krsort()to sort from newest to oldest (descending order):krsort($combinedNotes);Loop through and display
Now you can iterate over the sorted array to render your data:foreach ($combinedNotes as $timestamp => $note) { echo "Time: " . date('Y-m-d H:i:s', $timestamp) . "<br>"; echo "Author: " . $note['author'] . "<br>"; echo "Text: " . $note['text'] . "<br><br>"; // Add other fields as needed }
Option 2: Preserve All Entries (Even Duplicate Timestamps)
If you need to keep every entry—including those with matching timestamps—adjust your formatting to store entries in a numeric array (instead of using timestamps as keys), then sort with a custom comparator:
Adjust your formatting loop
Instead of assigning by timestamp key, push each entry into an array:// For each API response entry $formattedNotesAPI1[] = [ "time" => $noteTime, "text" => $noteText, "author" => $noteAuthor, "staffThread" => $note_ByStaff, "id" => $noteId ]; // Do the same for the second API to get $formattedNotesAPI2Merge and sort
Combine the arrays, then useusort()with a custom function to sort by thetimefield:$combinedNotes = array_merge($formattedNotesAPI1, $formattedNotesAPI2); // Sort oldest to newest usort($combinedNotes, function($a, $b) { return $a['time'] - $b['time']; }); // Or sort newest to oldest: // usort($combinedNotes, function($a, $b) { // return $b['time'] - $a['time']; // });Display the sorted data
Loop through the sorted numeric array:foreach ($combinedNotes as $note) { echo "Time: " . date('Y-m-d H:i:s', $note['time']) . "<br>"; echo "Author: " . $note['author'] . "<br>"; echo "Text: " . $note['text'] . "<br><br>"; }
Both methods work great—pick the one that fits your needs around duplicate timestamps!
内容的提问来源于stack exchange,提问作者Dominic Kirby

