2011-09-15 186 views
0

索引數組的數組,比方說,你有一個數組,看起來像這樣: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'); 

你怎麼能排序$ myarray的根據姓氏?

+0

可能重複:http://stackoverflow.com/questions/1905617/how-do-i-sort-multidimension-array-in-php – 2011-09-15 04:22:40

+0

和另一個重複:http://stackoverflow.com/questions/1795244/sorting-a-multidimensional-array-in-php/1795268#1795268 – 2011-09-15 04:23:08

回答

5

這也適用

<?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

這應該做你需要的東西:

<?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'); 

我使用uasort(),自定義排序功能之一,對排序。

3

我得到了它使用usort()和關閉工作。

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

對於PHP 5.3及更高版本... http://www.php.net/manual/en/functions.anonymous.php – StefanNch