![]() |
VOOZH | about |
Sorting a multi-dimensional array by key value in PHP can be useful in various scenarios, such as organizing data for display or processing. In this article, we will explore different approaches to achieve this.
Table of Content
This approach uses the array_multisort() function to sort a multi-dimensional array by a specified key.
Syntax:
array_multisort(array_column($array, 'key_to_sort_by'), SORT_ASC, $array);Example: This example uses array_multisort() function to sort the Multi-dimensional Array by Key Value in PHP.
Name: Manohar, Age: 20 Name: Prasad, Age: 25 Name: Saurabh, Age: 30
This approach uses a custom sorting function with the usort() function to sort a multi-dimensional array by a specified key.
Syntax:
usort($array, function($a, $b) {
return $a['key_to_sort_by'] <=> $b['key_to_sort_by'];
});
Example: This example uses custom sorting function with usort() to sort the Multi-dimensional Array by Key Value in PHP.
ID: 1, Name: Saurabh ID: 2, Name: Prasad ID: 3, Name: Manohar
This approach utilizes the uasort() function, which is similar to usort() but preserves the keys of the array, making it suitable when the keys themselves carry significance. A custom comparison function is provided to uasort() to dictate the sorting logic based on a specific key within the sub-arrays.
Syntax:
uasort($array, function($a, $b) {
return $a['key_to_sort_by'] <=> $b['key_to_sort_by'];
});
Example: In this example, we use uasort() to sort a multi-dimensional array by a key value, while maintaining the association between keys and elements. This is particularly useful when the keys are meaningful, such as identifiers or non-numeric indexing.
Array ( [1] => Array ( [id] => 1 [name] => Jane [age] => 22 ) [0] => Array ( [id] => 2 [name] => John ...
Using `array_walk()` and a custom sort logic involves iterating through the array and applying a user-defined sorting function to each element. This method ensures that each sub-array is sorted based on a specified key, providing a flexible approach for sorting multi-dimensional arrays.
Example
Array ( [0] => Array ( [id] => 2 [name] => John [age] => 28 ) [1] => Array ( [id] => 1 [name] => Jane ...