Is it possible to use usort
to sort multiple fields in a multidimensional array? For example, I want to sort name
alphabetically and then from those records I want to sort them by age
. Is this possible using sort
?
Array ( [0] => Array ( [name] => Jonah [age] => 27 ) [1] => Array ( [name] => Bianca [age] => 32 ) )
To sort more than four records at once, use the CTRL key to select multiple fields, right-click, then choose to sort in ascending or descending order. The fields are sorted in the order you click them in the table.
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
How about:
$arr = Array ( 0 => Array ( 'name' => 'Jonah', 'age' => '27', ), 1 => Array ( 'name' => 'Bianca', 'age' => '32', ), 2 => Array ( 'name' => 'Jonah', 'age' => '25', ), 3 => Array ( 'name' => 'Bianca', 'age' => '35', ), ); function comp($a, $b) { if ($a['name'] == $b['name']) { return $a['age'] - $b['age']; } return strcmp($a['name'], $b['name']); } usort($arr, 'comp'); print_r($arr);
output:
Array ( [0] => Array ( [name] => Bianca [age] => 32 ) [1] => Array ( [name] => Bianca [age] => 35 ) [2] => Array ( [name] => Jonah [age] => 25 ) [3] => Array ( [name] => Jonah [age] => 27 ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With