PHP sort an array of arrays according to an index in the arrays

馋奶兔 提交于 2019-12-11 15:28:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!