PHP根据数组中的索引对数组进行排序

时间:2022-03-05 21:33:19

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?

你如何根据姓氏对$ myArray进行排序?

3 个解决方案

#1


5  

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


3  

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

我使用usort()和一个闭包来使用它。

        usort($myArray, function($a, $b){
            return strcasecmp($a['lastname'], $b['lastname']);
        });

#3


2  

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.

我正在使用自定义排序函数之一uasort()来进行排序。

#1


5  

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


3  

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

我使用usort()和一个闭包来使用它。

        usort($myArray, function($a, $b){
            return strcasecmp($a['lastname'], $b['lastname']);
        });

#3


2  

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.

我正在使用自定义排序函数之一uasort()来进行排序。