2013-09-24 60 views
0

我有一个内部有8个数组的数组。按内部数组元素排序2维数组

它看起来像这样:

[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]] 

每个该内阵列具有作为其第一元素的数目。现在我想接收具有最大数字的外部数组的元素作为第一个元素。

我该怎么做?

非常感谢。

+3

你有什么试过?提示:['foreach()'](http://php.net/manual/en/control-structures.foreach.php) –

+0

调查['usort'](http://php.net/manual/en /function.usort.php) – Brian

回答

2

您可以使用PHP的usort()

usort($array, function($a, $b) { 
    return $a[0] > $b[0]; 
}); 

这将整理您的数组,到位,使得第一元素将有数量最多的,因为它是第一个元素定义任何排序算法。

+0

有没有人知道,为什么我得到这个错误:“解析错误:语法错误,意外的T_FUNCTION”通过使用? – progNewbie

+0

您使用的是什么版本的PHP?运行'php -v' – xbonez

1

对整个数组进行排序并不是必需的(而且更昂贵)。像这样的东西会工作:

// initially, regard the first element as the largest 
$element = $array[0]; 
$greatest = $array[0][0]; 

$length = count($array); 

// compare the first value of each array against $greatest, swapping $element if it's larger 
for($i = 1; $i < $length; $i++) { // N.B. start with second element 
    if($array[$i][0] > $greatest) { 
     $element = $array[$i]; 
    } 
} 

// $element is now the element with the biggest first value 
+0

我同意这种方法最好,如果你只需要具有最高价值的元素。虽然OP应该检查出usort以供将来参考,或者如果他们最终需要整个数组排序。 –