PHP - Sorting a multidimensional array
Array ( [data] => Array ( [0] => Array ( [name] => Nicki Escudero [id] => 27700035 ) [1] => Array ( [name] => Yorgo Nestoridis [id] => 504571368 ) ) )
How can I sort this multidimensional array using its name?
I tried with array_multisort but it's not working.
Answers
If you want to use array_multisort, you would use the following:
$array = array( 'data' => array( array( 'name' => 'Yorgo Nestoridis', 'id' => 504571368, ), array( 'name' => 'Nicki Escudero', 'id' => 27700035, ), ), ); $names = array(); foreach($array['data'] as $datum) { $names[] = $datum['name']; } array_multisort($names, SORT_ASC, $array['data']); var_dump($array); // now sorted by name
The other choice is to use a custom comparison function:
function compareNames($a, $b) { return strcmp($a['name'], $b['name']); } usort($array['data'], 'compareNames');
It is already sorted :-) What do you want to sort by? And where is the data coming from? if you get it from a DB you should sort differently.
If those are the only two values you have, you can try making id the index of the array and the name can be the value. You can then use asort to sort the array by name and maintain the index-value relation.
By making id the index, I mean $array[27700035] would return Nicki Escudero.
// Copy the array to a new array. foreach($array as $val) { $newArray[$val['id']] = $val['name']; } asort($newArray);
Edit: I've gone through the manual and you can also use usort with a custom comparison function. Although I've never used this and can be of very little help... PHP usort