PHP

Custom Sort Multidimensional Arrays by Multiple Keys

Learn to sort arrays of arrays or objects in PHP using `usort` with a custom comparison function for complex, multi-key sorting logic.

<?php

$users = [
    ['id' => 1, 'name' => 'Alice', 'age' => 30, 'city' => 'New York'],
    ['id' => 2, 'name' => 'Charlie', 'age' => 25, 'city' => 'Los Angeles'],
    ['id' => 3, 'name' => 'Bob', 'age' => 30, 'city' => 'Chicago'],
    ['id' => 4, 'name' => 'Alice', 'age' => 35, 'city' => 'Boston']
];

// Sort users primarily by 'age' (ascending), then by 'name' (ascending) for ties
usort($users, function($a, $b) {
    if ($a['age'] == $b['age']) {
        return strcmp($a['name'], $b['name']); // Sort by name if ages are equal
    }
    return ($a['age'] < $b['age']) ? -1 : 1; // Sort by age
});

print_r($users);

// Expected Output:
// Array
// (
//     [0] => Array
//         (
//             [id] => 2
//             [name] => Charlie
//             [age] => 25
//             [city] => Los Angeles
//         )
//     [1] => Array
//         (
//             [id] => 1
//             [name] => Alice
//             [age] => 30
//             [city] => New York
//         )
//     [2] => Array
//         (
//             [id] => 3
//             [name] => Bob
//             [age] => 30
//             [city] => Chicago
//         )
//     [3] => Array
//         (
//             [id] => 4
//             [name] => Alice
//             [age] => 35
//             [city] => Boston
//         )
// )

// Sort by 'city' (descending) then 'age' (ascending)
usort($users, function($a, $b) {
    $cityComparison = strcmp($b['city'], $a['city']); // Descending city
    if ($cityComparison !== 0) {
        return $cityComparison;
    }
    return ($a['age'] < $b['age']) ? -1 : 1; // Ascending age for same city
});

print_r($users);
How it works: The `usort` function allows sorting an array by a user-defined comparison function, which is invaluable for complex sorting scenarios, especially with multidimensional arrays or objects. The callback function receives two elements (`$a`, `$b`) and should return -1 if `$a` comes before `$b`, 1 if `$a` comes after `$b`, or 0 if they are equal. This enables sorting by multiple keys (e.g., primary sort by 'age', secondary sort by 'name' for ties) and applying custom logic for different data types or desired order (ascending/descending).

Need help integrating this into your project?

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

Hire DigitalCodeLabs