PHP sort an array of arrays according to an index

2019-08-19 01:50发布

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?

3条回答
Emotional °昔
2楼-- · 2019-08-19 02:09

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.

查看更多
Viruses.
3楼-- · 2019-08-19 02:14

I got it to work using usort() and a closure.

        usort($myArray, function($a, $b){
            return strcasecmp($a['lastname'], $b['lastname']);
        });
查看更多
Emotional °昔
4楼-- · 2019-08-19 02:24

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>';
查看更多
登录 后发表回答