How to sort a multidimensional array based on key?
How to sort a multidimensional array based on key?
First of all, let’s give credit to the person who wrote this function.
The problem ?
Let’s say you have a multidimensional array and you want to sort based on a key that is not on the first level of the array, how would you do that ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$people = array( 12345 => array( 'id' => 12345, 'first_name' => 'Joe', 'surname' => 'Bloggs', 'age' => 23, 'sex' => 'm' ), 12346 => array( 'id' => 12346, 'first_name' => 'Adam', 'surname' => 'Smith', 'age' => 18, 'sex' => 'm' ), 12347 => array( 'id' => 12347, 'first_name' => 'Amy', 'surname' => 'Jones', 'age' => 21, 'sex' => 'f' ) ); |
Given this array, you will want probably to sort based on “age” or “sex”, keys that are in the second level or arrays. You can obtain that with the following function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
function array_sort($array, $on, $order=SORT_ASC) { $new_array = array(); $sortable_array = array(); if (count($array) > 0) { foreach ($array as $k => $v) { if (is_array($v)) { foreach ($v as $k2 => $v2) { if ($k2 == $on) { $sortable_array[$k] = $v2; } } } else { $sortable_array[$k] = $v; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $k => $v) { $new_array[$k] = $array[$k]; } } return $new_array; } |
Calling this function with the appropriate parameters, allow you to obtain the desired structure, so:
1 |
var_dump( array_sort($people, 'age') ); |
will output this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
array (size=3) 12346 => array (size=5) 'id' => int 12346 'first_name' => string 'Adam' (length=4) 'surname' => string 'Smith' (length=5) 'age' => int 18 'sex' => string 'm' (length=1) 12347 => array (size=5) 'id' => int 12347 'first_name' => string 'Amy' (length=3) 'surname' => string 'Jones' (length=5) 'age' => int 21 'sex' => string 'f' (length=1) 12345 => array (size=5) 'id' => int 12345 'first_name' => string 'Joe' (length=3) 'surname' => string 'Bloggs' (length=6) 'age' => int 23 'sex' => string 'm' (length=1) |
You can sort on any other key. It’s your choice, I`m here just to provide this good function further to the people who need it 🙂