2016-11-13 80 views
0

我在PHP中的數組:排序陣列上的任意鍵

$myarray[$index]['height'] 
$myarray[$index]['weight'] 
$myarray[$index]['age'] 

這是任何一個鍵「高度」,「重」或「年齡」的排序最好的功能?

一個例子,如果我在輸入

$myarray[0]['height'] = 175; 
$myarray[0]['weight'] = 68; 
$myarray[0]['age'] = 44; 

$myarray[1]['height'] = 166; 
$myarray[1]['weight'] = 82; 
$myarray[1]['age'] = 56; 

$myarray[2]['height'] = 188; 
$myarray[2]['weight'] = 82; 
$myarray[2]['age'] = 35; 

,我想按年齡排序,我獲得

$myarray[0]['height'] = 188; 
$myarray[0]['weight'] = 82; 
$myarray[0]['age'] = 35; 

$myarray[1]['height'] = 175; 
$myarray[1]['weight'] = 68; 
$myarray[1]['age'] = 44; 

$myarray[2]['height'] = 166; 
$myarray[2]['weight'] = 82; 
$myarray[2]['age'] = 56; 
+0

[usort()](http://php.net/manual/en/function.usort.php)將您想要排序的列傳遞給回調 –

回答

1

有一個在usort documentation自定義排序多維數組一個很好的例子。

Here's a fiddle.

<?php 
$myarray[0]['height'] = 175; 
$myarray[0]['weight'] = 68; 
$myarray[0]['age'] = 44; 

$myarray[1]['height'] = 166; 
$myarray[1]['weight'] = 82; 
$myarray[1]['age'] = 56; 

$myarray[2]['height'] = 188; 
$myarray[2]['weight'] = 82; 
$myarray[2]['age'] = 35; 

function build_sorter($key) { 
    return function ($a, $b) use ($key) { 
     return strnatcmp($a[$key], $b[$key]); 
    }; 
} 

usort($myarray, build_sorter('age')); 

print_r($myarray); 
Array 
(
    [0] => Array 
     (
      [height] => 188 
      [weight] => 82 
      [age] => 35 
     ) 

    [1] => Array 
     (
      [height] => 175 
      [weight] => 68 
      [age] => 44 
     ) 

    [2] => Array 
     (
      [height] => 166 
      [weight] => 82 
      [age] => 56 
     ) 

) 
+0

謝謝,但是strnatcmp是比較的正確函數號碼? – Ivo

+0

它適用於我,但當然您可以修改/替換它以滿足您的需求。 –

0

所以基本上你需要的是按列排序的數組。

function sortByColumn(&$array, $column, $order = SORT_ASC) 
{ 
    array_multisort(
     array_column($array, $column), 
     $order, 
     $array 
    ); 
} 

這種方法是使用array_multisortarray_column功能:下面的代碼將這樣的伎倆。

也可以這樣指定順序(SORT_ASC或SORT_DESC)。

這是working demo