我有一個內部有8個數組的數組。按內部數組元素排序2維數組
它看起來像這樣:
[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]]
每個該內陣列具有作爲其第一元素的數目。現在我想接收具有最大數字的外部數組的元素作爲第一個元素。
我該怎麼做?
非常感謝。
我有一個內部有8個數組的數組。按內部數組元素排序2維數組
它看起來像這樣:
[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]]
每個該內陣列具有作爲其第一元素的數目。現在我想接收具有最大數字的外部數組的元素作爲第一個元素。
我該怎麼做?
非常感謝。
您可以使用PHP的usort()
usort($array, function($a, $b) {
return $a[0] > $b[0];
});
這將整理您的數組,到位,使得第一元素將有數量最多的,因爲它是第一個元素定義任何排序算法。
有沒有人知道,爲什麼我得到這個錯誤:「解析錯誤:語法錯誤,意外的T_FUNCTION」通過使用? – progNewbie
您使用的是什麼版本的PHP?運行'php -v' – xbonez
對整個數組進行排序並不是必需的(而且更昂貴)。像這樣的東西會工作:
// 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
我同意這種方法最好,如果你只需要具有最高價值的元素。雖然OP應該檢查出usort以供將來參考,或者如果他們最終需要整個數組排序。 –
退房usort
:http://php.net/manual/en/function.usort.php
你必須編寫自己的比較函數。
你有什麼試過?提示:['foreach()'](http://php.net/manual/en/control-structures.foreach.php) –
調查['usort'](http://php.net/manual/en /function.usort.php) – Brian