PHP
Dynamically Sort Array of Associative Arrays by Key
Learn how to sort a multi-dimensional PHP array (an array of associative arrays) by any specified key and in any order (ascending/descending) using `usort` and a custom comparison function.
<?php
function sortByDynamicKey(array $data, string $key, string $order = 'asc'): array
{
usort($data, function ($a, $b) use ($key, $order) {
if (!isset($a[$key]) || !isset($b[$key])) {
return 0; // Handle cases where key might be missing
}
$valueA = $a[$key];
$valueB = $b[$key];
if (is_numeric($valueA) && is_numeric($valueB)) {
$comparison = $valueA <=> $valueB;
} else {
$comparison = strcmp((string)$valueA, (string)$valueB);
}
return ($order === 'desc') ? -$comparison : $comparison;
});
return $data;
}
$products = [
['id' => 3, 'name' => 'Laptop', 'price' => 1200],
['id' => 1, 'name' => 'Mouse', 'price' => 25],
['id' => 2, 'name' => 'Keyboard', 'price' => 75],
];
$sortedByNameAsc = sortByDynamicKey($products, 'name');
// var_dump($sortedByNameAsc);
$sortedByPriceDesc = sortByDynamicKey($products, 'price', 'desc');
// var_dump($sortedByPriceDesc);
?>
How it works: This snippet provides a function `sortByDynamicKey` that sorts an array of associative arrays. It uses `usort` with a closure to define the custom comparison logic. The closure dynamically accesses the specified `$key` for comparison and uses the spaceship operator (`<=>`) for numeric values or `strcmp` for strings, respecting the `$order` (asc/desc).