简体   繁体   中英

Sort keys of associative array with usort

I have an associative array with the $category (title of the category) as key and the $auditElement as value:

foreach ($auditElements as $auditElement) {
    $category = $auditElement->getAuditCategory()->getTitle();
    if (!array_key_exists($category, $groupedEntries)) {
        $groupedEntries[$category] = [];
        $auditCategories[$category] = $auditElement->getAuditCategory()->getSequenceIndex();
    }

    $groupedEntries[$category][] = $auditElement;
}

Now I want to sort this array $groupedEntries by the sequenceIndex of the category. Therefore I have saved the sequenceIndex of the category in an extra array $auditCategories with the $category as key and the sequenceIndex as value.

My idea was to use usort or uasort to sort the $groupedEntries by the sequenceIndex:

uasort($groupedEntries, function ($cat1, $cat2) use ($auditCategories) {
    $idx1 = $auditCategories[$cat1];
    $idx2 = $auditCategories[$cat2];
    return ($idx1 == $idx2) ? 0 : ($idx1 > $idx2]) ? 1 : -1;
});

But I get an error because the elements in the comparison function aren't the single array elements but the value array associated with the key:

Illegal offset type

As $groupedEntries is array of arrays, $cat1 (and $cat2 ) are subarrays. Instead, try uksort , here, you will receive keys as comparing values:

uksort($groupedEntries, function ($cat1, $cat2) use ($auditCategories) {
    $idx1 = $auditCategories[$cat1];
    $idx2 = $auditCategories[$cat2];
    return ($idx1 == $idx2) ? 0 : ($idx1 > $idx2]) ? 1 : -1;
    // you can replace last line with
    // return $idx1 - $idx2; 
    // or if you want to be more precise and you have php7
    // return $idx1 <=> $idx2;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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