Home > Article > Backend Development > How to Sort a Multi-Dimensional PHP Array by an Inner Array Value?
Sorting a Multi-Dimensional PHP Array by an Inner Array Value
To sort a multi-dimensional PHP array based on a specific value in the inner array, you can employ a custom sorting function.
Custom Sorting Function:
<code class="php">function array_sort($array, $on, $order = SORT_ASC) { $new_array = []; $sortable_array = []; if (count($array) > 0) { foreach ($array as $key => $value) { if (is_array($value)) { foreach ($value as $key2 => $value2) { if ($key2 == $on) { $sortable_array[$key] = $value2; } } } else { $sortable_array[$key] = $value; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $key => $value) { $new_array[$key] = $array[$key]; } } return $new_array; }</code>
Usage:
<code class="php">$list = array( array('type' => 'suite', 'name' => 'A-Name'), array('type' => 'suite', 'name' => 'C-Name'), array('type' => 'suite', 'name' => 'B-Name') ); $list = array_sort($list, 'name', SORT_ASC); print_r($list);</code>
Output:
<code class="php">array(3) { [0]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "A-Name" } [2]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "B-Name" } [1]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "C-Name" } }</code>
The above is the detailed content of How to Sort a Multi-Dimensional PHP Array by an Inner Array Value?. For more information, please follow other related articles on the PHP Chinese website!