Sorting a Multidimensional Array by Sub-array Value in PHP
In PHP, arrays can be multidimensional, meaning they can contain arrays within arrays. A common use case is to sort such arrays based on a specific key within the nested sub-arrays.
Sorting by a String Key
Consider the following array:
$array = [ [ 'configuration_id' => 10, 'id' => 1, 'optionNumber' => '3', 'optionActive' => 1, 'lastUpdated' => '2010-03-17 15:44:12' ], [ 'configuration_id' => 9, 'id' => 1, 'optionNumber' => '2', 'optionActive' => 1, 'lastUpdated' => '2010-03-17 15:44:12' ], [ 'configuration_id' => 8, 'id' => 1, 'optionNumber' => '1', 'optionActive' => 1, 'lastUpdated' => '2010-03-17 15:44:12' ] ];
To sort this array in ascending order based on the 'optionNumber' key, we can use usort along with an anonymous function:
usort($array, function ($a, $b) { return strcmp($a['optionNumber'], $b['optionNumber']); });
This function compares the 'optionNumber' values of each sub-array and returns 1 if the first value is greater, -1 if it's smaller, or 0 if they're equal. This comparison is case-sensitive.
Sorting by an Integer Key
If the 'optionNumber' key contains integers, we can use the following function:
usort($array, function ($a, $b) { return $a['optionNumber'] - $b['optionNumber']; });
This comparison will sort the array in ascending numerical order.
Considerations
The above is the detailed content of How to Sort a Multidimensional PHP Array by Sub-array Value?. For more information, please follow other related articles on the PHP Chinese website!