phparrayssortingasort

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


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?


Solution

  • 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>';