Home >Backend Development >PHP Tutorial >How to Sort Multi-Dimensional Arrays Based on Inner Array Value in PHP?
Arrays in PHP provide a powerful data structure for organizing and storing data. However, sorting multi-dimensional arrays based on a specific value within an inner array can be a challenging task.
Consider a PHP hashtable with the following data structure:
[ [ "type" => "suite", "name" => "A-Name" ], [ "type" => "suite", "name" => "C-Name" ], [ "type" => "suite", "name" => "B-Name" ] ]
The goal is to sort this data structure based on the "name" key in the inner array.
Various PHP functions can be used for sorting arrays:
However, none of these functions directly support sorting based on a key within an inner array.
To overcome this limitation, a custom sort function can be defined to compare the desired values within the inner array. This can be accomplished using the usort function.
<code class="php">function cmp($a, $b) { return $b['name'] - $a['name']; }</code>
This function compares the "name" key in the inner arrays and returns a negative value if the first array's name is greater than the second array's name.
Once the comparison function is defined, it can be used to sort the array using the usort function.
<code class="php">usort($mydata, "cmp");</code>
An alternative solution to the custom sort function is to create a new array that contains only the values to be sorted. This can be done with a nested loop and a conditional statement.
<code class="php">function array_sort($array, $on, $order=SORT_ASC) { // ... return $new_array; }</code>
This function takes in the array to be sorted, the key to sort on, and an optional order (ascending or descending). It returns a new array with the sorted data.
The array_sort function can be used as follows:
<code class="php">$mydata = [ ['type' => 'suite', 'name' => 'A-Name'], ['type' => 'suite', 'name' => 'C-Name'], ['type' => 'suite', 'name' => 'B-Name'] ]; $sorted_data = array_sort($mydata, 'name', SORT_ASC); print_r($sorted_data);</code>
The above is the detailed content of How to Sort Multi-Dimensional Arrays Based on Inner Array Value in PHP?. For more information, please follow other related articles on the PHP Chinese website!