Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usort sorting multiple fields

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      ) ) 
like image 749
user1205775 Avatar asked Feb 13 '12 12:02

user1205775


People also ask

What is necessary to sort by multiple fields?

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.

Can you sort a multidimensional array?

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.

How do I sort a multidimensional array in PHP?

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.


1 Answers

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         )  ) 
like image 70
Toto Avatar answered Oct 19 '22 22:10

Toto