PHP
Sort Multi-dimensional Arrays by a Key
Learn to sort complex multi-dimensional PHP arrays efficiently by the values of a specific key using a custom comparison function with `usort`.
<?php
$users = [
['id' => 1, 'name' => 'Bob', 'age' => 25],
['id' => 2, 'name' => 'Alice', 'age' => 30],
['id' => 3, 'name' => 'Charlie', 'age' => 20],
];
echo "Original Users:
";
print_r($users);
// Sort users by age in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // PHP 7+ spaceship operator
});
echo "Users Sorted by Age (Ascending):
";
print_r($users);
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75],
];
echo "Original Products:
";
print_r($products);
// Sort products by price in descending order
usort($products, function($a, $b) {
return $b['price'] <=> $a['price']; // Descending
});
echo "Products Sorted by Price (Descending):
";
print_r($products);
?>
How it works: This snippet showcases how to sort a multi-dimensional array based on the value of a specific key within its inner arrays using `usort()`. The function takes the array and a custom comparison callback. The callback receives two elements (`$a`, `$b`) and should return `0` if they are equal, `-1` if `$a` should come before `$b`, and `1` if `$b` should come before `$a`. The PHP 7+ spaceship operator (`<=>`) simplifies this comparison.