PHP

Sort Array of Associative Arrays by Nested Key

Master sorting complex PHP arrays containing associative arrays by a specific key, including nested keys, using `usort` with a custom comparison function for flexible ordering.

<?php

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

// Sort by 'age' (nested key) ascending, then by 'name' ascending
usort($users, function($a, $b) {
    $ageA = $a['details']['age'] ?? 0;
    $ageB = $b['details']['age'] ?? 0;

    if ($ageA == $ageB) {
        return strcmp($a['name'], $b['name']); // Secondary sort by name
    }
    return $ageA <=> $ageB; // Primary sort by age
});

print_r($users);
/*
Output (sorted by age ascending, then name ascending for same age):
Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Bob
            [details] => Array
                (
                    [age] => 25
                    [city] => Los Angeles
                )
        )
    [1] => Array
        (
            [id] => 4
            [name] => David
            [details] => Array
                (
                    [age] => 25
                    [city] => Houston
                )
        )
    [2] => Array
        (
            [id] => 1
            [name] => Alice
            [details] => Array
                (
                    [age] => 30
                    [city] => New York
                )
        )
    [3] => Array
        (
            [id] => 3
            [name] => Charlie
            [details] => Array
                (
                    [age] => 35
                    [city] => Chicago
                )
        )
)
*/
How it works: This snippet demonstrates how to sort an array of associative arrays ($users) based on a nested key (age) and then a secondary key (name) for tie-breaking. It uses `usort` with a custom comparison function that leverages PHP 7's spaceship operator (<=>) for efficient numeric comparison and `strcmp` for string comparisons.

Need help integrating this into your project?

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

Hire DigitalCodeLabs