Let's say you have an array that looks like this:
$myArray []= array('firstname' => 'John' , 'lastname'=> 'Johnson');
$myArray []= array('firstname' => 'Adam' , 'lastname'=> 'Tyson');
$myArray []= array('firstname' => 'Mike' , 'lastname'=> 'Robinson');
$myArray []= array('firstname' => 'David' , 'lastname'=> 'Jackson');
How can you sort $myArray according to the lastname?
This also works
<?php
$myArray []= array('firstname' => 'John' , 'lastname'=> 'Johnson');
$myArray []= array('firstname' => 'Adam' , 'lastname'=> 'Tyson');
$myArray []= array('firstname' => 'Mike' , 'lastname'=> 'Robinson');
$myArray []= array('firstname' => 'David' , 'lastname'=> 'Jackson');
foreach ($myArray as $array) {
$lastnames[] = $array['lastname'];
}
array_multisort($lastnames,SORT_STRING,$myArray);
echo '<pre>',print_r($myArray,1),'</pre>';
I got it to work using usort() and a closure.
usort($myArray, function($a, $b){
return strcasecmp($a['lastname'], $b['lastname']);
});
This should do what you need:
<?php
function cmp($a, $b) {
return strcasecmp($a['lastname'], $b['lastname']);
}
$myArray[] = array('firstname' => 'John', 'lastname'=> 'Johnson');
$myArray[] = array('firstname' => 'Adam', 'lastname'=> 'Tyson');
$myArray[] = array('firstname' => 'Mike', 'lastname'=> 'Robinson');
$myArray[] = array('firstname' => 'David', 'lastname'=> 'Jackson');
uasort($myArray, 'cmp');
I'm using uasort()
, one of the custom sort function, to the sorting.