2015-10-13 164 views
0
$student_data = array(
array(
    "id" => 1, 
    "student_name" => "Kasimir Clark", 
    "country" => "Chile" 
), 
array(
    "id" => 2, 
    "student_name" => "Kyle Myers", 
    "country" => "Cook Islands" 
), 
array(
    "id" => 3, 
    "student_name" => "Merrill Velez", 
    "country" => "Israel" 
), 
array(
    "id" => 4, 
    "student_name" => "Kadeem Graham", 
    "country" => "Christmas Island" 
), 
); 

usort($student_data, function($a, $b) 
{ 
    return $a["student_name"] - $b["student_name"]; 
}); 

我需要排序PHP中的多維數組。是否可以按名稱對國家進行分類?我試圖用usort來實現,但我只能按照一個條件來排序,比如名字或國家。多維數組排序在PHP中

我想實現類似於MySQL數據庫正在做的事情。 喜歡的東西

SELECT * FROM STUDENT order by country,name

謝謝您的幫助。

+0

顯示你已經嘗試過的情況。 –

+0

你的答案在http://stackoverflow.com/questions/16306416/sort-php-multi-dimensional-array-based-on-key –

+0

我想按國家排序,然後按名稱。類似於SQL命令通過不同的列。 – Ralph

回答

3

使用array_multisort,我在comments中發現了一個實現。

function array_orderby() 
{ 
    $args = func_get_args(); 
    $data = array_shift($args); 
    foreach ($args as $n => $field) { 
     if (is_string($field)) { 
      $tmp = array(); 
      foreach ($data as $key => $row) 
       $tmp[$key] = $row[$field]; 
      $args[$n] = $tmp; 
      } 
    } 
    $args[] = &$data; 
    call_user_func_array('array_multisort', $args); 
    return array_pop($args); 
} 

$student_data = array(
    array(
     "id" => 1, 
     "student_name" => "Kasimir Clark", 
     "country" => "Chile" 
    ), 
    array(
     "id" => 2, 
     "student_name" => "Kyle Myers", 
     "country" => "Cook Islands" 
    ), 
    array(
     "id" => 3, 
     "student_name" => "Merrill Velez", 
     "country" => "Israel" 
    ), 
    array(
     "id" => 4, 
     "student_name" => "Kadeem Graham", 
     "country" => "Christmas Island" 
    ) 
); 


$sorted = array_orderby($student_data, 'country', SORT_ASC, 'student_name', SORT_ASC); 

print_r($sorted); 

本刊:

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [student_name] => Kasimir Clark 
      [country] => Chile 
     ) 

    [1] => Array 
     (
      [id] => 4 
      [student_name] => Kadeem Graham 
      [country] => Christmas Island 
     ) 

    [2] => Array 
     (
      [id] => 2 
      [student_name] => Kyle Myers 
      [country] => Cook Islands 
     ) 

    [3] => Array 
     (
      [id] => 3 
      [student_name] => Merrill Velez 
      [country] => Israel 
     ) 

) 
+0

謝謝。這是工作! – Ralph