PHP

Custom Sorting Associative Arrays by Multiple Keys

Implement custom sorting for an array of associative arrays in PHP, allowing you to sort by one or more specific keys in ascending or descending order.

$employees = [
    ['name' => 'John Doe', 'age' => 30, 'salary' => 60000],
    ['name' => 'Jane Smith', 'age' => 25, 'salary' => 75000],
    ['name' => 'Peter Jones', 'age' => 30, 'salary' => 50000],
    ['name' => 'Alice Brown', 'age' => 35, 'salary' => 75000],
];

// Sort by salary (descending), then by age (ascending), then by name (ascending)
usort($employees, function ($a, $b) {
    // Primary sort: salary descending
    if ($a['salary'] !== $b['salary']) {
        return $b['salary'] <=> $a['salary']; // Spaceship operator (PHP 7+)
    }

    // Secondary sort: age ascending
    if ($a['age'] !== $b['age']) {
        return $a['age'] <=> $b['age'];
    }

    // Tertiary sort: name ascending
    return $a['name'] <=> $b['name'];
});

/*
$employees will be sorted as:
[
    ['name' => 'Alice Brown', 'age' => 35, 'salary' => 75000],
    ['name' => 'Jane Smith', 'age' => 25, 'salary' => 75000],
    ['name' => 'John Doe', 'age' => 30, 'salary' => 60000],
    ['name' => 'Peter Jones', 'age' => 30, 'salary' => 50000],
]
*/
How it works: This snippet demonstrates how to perform custom multi-level sorting on an array of associative arrays using `usort`. A custom comparison function is provided, which first compares elements by 'salary' in descending order. If salaries are equal, it then compares by 'age' in ascending order, and finally by 'name' in ascending order if both salary and age are identical. The spaceship operator (`<=>`) is used for concise comparison.

Need help integrating this into your project?

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

Hire DigitalCodeLabs