Home >Backend Development >PHP Tutorial >How to Sort a Multi-Dimensional Array in PHP by a Specific Key?
Sorting Multi-Dimensional Arrays by a Specific Key
Sorting multi-dimensional arrays by a specific key value can be achieved using various methods in PHP. Let's explore a common problem and its solutions using this technique.
Problem:
How do we sort an array based on the "order" key?
Array's Structure:
$myArray = [ [ 'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4', 'title' => 'Flower', 'order' => 3 ], [ 'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594', 'title' => 'Free', 'order' => 2 ], [ 'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b', 'title' => 'Ready', 'order' => 1 ] ];
Solutions:
1. Using usort with a Custom Function:
This method involves defining a custom sorting function that compares the "order" values and returns an appropriate comparison result.
function sortByOrder($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; } usort($myArray, 'sortByOrder');
2. Using Anonymous Functions:
In PHP 5.3 and later, anonymous functions can be used to simplify the custom sorting function.
usort($myArray, function($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; });
3. Using the Spaceship Operator (PHP 7 and later):
PHP 7 introduced the spaceship operator (< =>) for concise comparison operations. 4. Using Arrow Functions (PHP 7.4 and later): Arrow functions further simplify code by eliminating the function keyword. Multi-Dimensional Sorting: For arrays with nested structures, you can extend the sorting function to consider multiple keys. This allows for complex sorting, such as sorting by "order" within "suborder." Note: If you need to maintain key associations, consider using uasort() instead of usort(). The above is the detailed content of How to Sort a Multi-Dimensional Array in PHP by a Specific Key?. For more information, please follow other related articles on the PHP Chinese website!usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});