简体   繁体   English

我需要合并和排序两个多级PHP数组

[英]I need to merge and sort two multi-level PHP arrays

I'm trying to merge two multi-level arrays into one and then sort them by time. 我正在尝试将两个多级数组合并为一个,然后按时间对其进行排序。 This is because I'm making two different API calls to a PSA and then I need to present the data in order. 这是因为我要对PSA进行两个不同的API调用,然后需要按顺序显示数据。 I've formatted each array like the example below (using a foreach loop to reformat the entries returned by the API into something consistent): 我已经像下面的示例一样格式化了每个数组(使用foreach循环将API返回的条目重新格式化为一致的格式):

$formattedNotes[$noteTime] = Array(
                "text" => $noteText,
                "author" => $noteAuthor,
                "staffThread" => $note_ByStaff,
                "id" => $noteId
            );

$entryTime is an epoch time associated with that record, and the array of both datasets are identical (each has text, author, staffThread, and id). $entryTime是与该记录关联的纪元时间,两个数据集的数组相同(每个数据集都有文本,作者,staffThread和id)。 My goal is to merge these two arrays, and then sort them by $entryTime 我的目标是合并这两个数组,然后按$entryTime对其进行排序

I've tried the following, but it still doesn't seem to come out sorted: 我已经尝试了以下方法,但是它似乎仍然没有排序:

public static function MergeTimeAndNotesIntoArray($time, $notes)
{
    ksort($time);
    ksort($notes);
    $result = array_merge($time, $notes);
    return $result;
}

If I understand this question correctly, something like this should do the trick: 如果我正确地理解了这个问题,那么应该采取以下措施:

public static function MergeTimeAndNotesIntoArray($time, $notes)
{
    $sorted = $time; // start with notes from $time
    foreach ($notes as $key => $value) { // add notes from $notes preserving keys
        $sorted[$key] = $value;
    }
    ksort($sorted); // sort everything by key
    return $sorted;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM