2013-01-15 53 views
0

可能重複:
How do I sort a multidimensional array in phpPHP排序多維數組的最佳方法?

可以說我有以下多維數組:

$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45"); 
$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71"); 
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11"); 

後來想通過其price這個$fruits[]數組排序。
所以應該是:

$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71"); 
$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45"); 
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11"); 

然後我上網各地的網絡了很多,終於讓我找到下面一個從php manual(我調整上面我的數組變量名):

// Obtain a list of columns 
foreach ($fruits as $key => $value) { 
    $name[$key] = $value['name']; 
    $price[$key] = $value['price']; 
    $code[$key] = $value['code']; 
} 

// Sort the data with volume descending, edition ascending 
// Add $data as the last parameter, to sort by the common key 
array_multisort($price, SORT_ASC, $fruits); 

OK , 得到它了!然後$fruits[]數組正確排序price值。
好了,下面是我的一些顧慮:

  • 至於我以前學過,我們不應該添加/使用任何附加/定製代碼使用排序Machinism。 (相反,我相信我們應該使用純內置方法。)
  • 在這裏,我懷疑它的性能,因爲它內部有預定製的foreach循環,這可能極大地降低了速度,同時我們擁有真正龐大的陣列。 (像我現在有)

所以現在我要問的是:

  • 是否PHP有任何純粹的方法來實現這個東西?
  • [或]我們不能糾正這個多維數組排序問題只使用 /從一些PHP純內置,數組排序方法(例如:sort(),usort(), asort(),array_multisort()等等。)?

回答

2
usort ($fruits, function($a, $b) { return $a['price'] > $b['price'] ? 1 : ($a['price'] == $b['price'] ? 0 : -1); }); 
+0

哇,完美的作品! –

0

usort聽起來就像你在找什麼:

<? 
$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45"); 
$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71"); 
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11"); 
usort($fruits, function($a, $b){return $a['price'] - $b['price'];}); 
print_r($fruits); 
?> 

生產:

Array 
(
    [0] => Array 
     (
      [name] => apple 
      [price] => 2 
      [code] => W71 
     ) 

    [1] => Array 
     (
      [name] => orange 
      [price] => 3 
      [code] => A45 
     ) 

    [2] => Array 
     (
      [name] => grape 
      [price] => 4 
      [code] => G11 
     ) 

)