PHP
Sort an Associative Array by a Specific Column
Learn how to efficiently sort a PHP array of associative arrays (e.g., users, products) by the value of a specific key, like 'price' or 'name', using array_multisort.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'price' => 25],
['id' => 3, 'name' => 'Keyboard', 'price' => 75],
['id' => 4, 'name' => 'Monitor', 'price' => 300]
];
// Sort by 'price' in ascending order
$prices = array_column($products, 'price');
array_multisort($prices, SORT_ASC, $products);
echo "Sorted by price ASC:
";
print_r($products);
// Sort by 'name' in descending order
$names = array_column($products, 'name');
array_multisort($names, SORT_DESC, $products);
echo "
Sorted by name DESC:
";
print_r($products);
?>
How it works: This snippet demonstrates how to sort an array of associative arrays by a specific key (column) using `array_multisort`. First, `array_column` extracts all values for the desired key into a separate array. Then, `array_multisort` uses this extracted array to determine the sort order for the original array, preserving key-value associations. It's an efficient method for sorting complex datasets based on specific criteria.