Sorting Multi-Dimensional Arrays by Value
Sorting data by a specific key value in a multi-dimensional array is a common task. This can be achieved through the use of a user-defined sorting function in conjunction with the usort() or uasort() function.
To sort an array by the "order" key, the following steps can be followed:
function sortByOrder($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; }
usort($myArray, 'sortByOrder');
usort($myArray, function($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; });
usort($myArray, function($a, $b) { return $a['order'] <=> $b['order']; });
usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);
Multi-Dimensional Sorting:
To extend sorting to multiple dimensions, the sorting function can be used recursively:
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; });
Preserving Key Associations:
To maintain key associations during sorting, use uasort() instead of usort(). See the PHP manual for a comparison of array sorting functions.
The above is the detailed content of How Can I Sort Multi-Dimensional Arrays in PHP by Value?. For more information, please follow other related articles on the PHP Chinese website!