问题
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?
回答1:
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>';
回答2:
I got it to work using usort() and a closure.
usort($myArray, function($a, $b){
return strcasecmp($a['lastname'], $b['lastname']);
});
回答3:
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.
来源:https://stackoverflow.com/questions/7425799/php-sort-an-array-of-arrays-according-to-an-index-in-the-arrays