PHP

Sort PHP Array of Associative Arrays by Multiple Keys

Implement complex sorting logic for an array of associative arrays by defining multiple keys and their sorting directions (ASC/DESC).

function sort_by_multiple_keys(array $array, array $sortFields): array
{
    usort($array, function ($a, $b) use ($sortFields) {
        foreach ($sortFields as $field => $direction) {
            if (isset($a[$field]) && isset($b[$field])) {
                if ($a[$field] === $b[$field]) {
                    continue; // Values are equal, move to the next sort field
                }
                $cmp = ($a[$field] < $b[$field]) ? -1 : 1;
                return ($direction === 'DESC') ? -$cmp : $cmp;
            }
        }
        return 0; // All sort fields were equal or not found
    });
    return $array;
}

$users = [
    ['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
    ['name' => 'Bob', 'age' => 25, 'city' => 'London'],
    ['name' => 'Charlie', 'age' => 30, 'city' => 'New York'],
    ['name' => 'David', 'age' => 25, 'city' => 'Paris'],
];

$sortedUsers = sort_by_multiple_keys($users, [
    'age' => 'ASC',
    'name' => 'ASC'
]);
/* Expected:
[
    ['name' => 'Bob', 'age' => 25, 'city' => 'London'],
    ['name' => 'David', 'age' => 25, 'city' => 'Paris'],
    ['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
    ['name' => 'Charlie', 'age' => 30, 'city' => 'New York'],
]
*/
print_r($sortedUsers);
How it works: This function sorts an array of associative arrays by multiple specified keys, each with an ascending or descending direction. It uses `usort` with a custom comparison callback that iterates through the provided `sortFields`. If values for a field differ, it returns the comparison result; otherwise, it moves to the next field until a difference is found or all fields are compared.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs