PHP
Sort Associative Arrays by Key Value in PHP
Discover how to efficiently sort an array containing multiple associative arrays based on the values of a specified key using PHP's powerful `usort` function.
function sortAssociativeArrayByKey(array &$array, string $key, bool $descending = false): void {
usort($array, function($a, $b) use ($key, $descending) {
if (!isset($a[$key]) || !isset($b[$key])) {
return 0; // Or handle error appropriately
}
$valueA = $a[$key];
$valueB = $b[$key];
if (is_numeric($valueA) && is_numeric($valueB)) {
return $descending ? ($valueB <=> $valueA) : ($valueA <=> $valueB);
} else {
return $descending ? strnatcmp($valueB, $valueA) : strnatcmp($valueA, $valueB);
}
});
}
// Example Usage:
$products = [
['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
['name' => 'Mouse', 'price' => 25, 'category' => 'Accessories'],
['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics'],
];
echo "
Sorted by price (ascending):
";
sortAssociativeArrayByKey($products, 'price');
print_r($products);
echo "
Sorted by name (descending):
";
sortAssociativeArrayByKey($products, 'name', true);
print_r($products);
How it works: This function `sortAssociativeArrayByKey` sorts an array of associative arrays based on the value of a specific key. It uses `usort`, which sorts an array by values using a user-defined comparison function. The comparison function checks if the key exists in both arrays, then compares their values. It handles both numeric and string comparisons, using the spaceship operator (`<=>`) for numbers and `strnatcmp` for natural order string comparison, with an option for ascending or descending order.