我有一个数组,里面有 8 个数组。
它看起来像这样:
[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]]
每个内部数组的第一个元素都有一个数字。现在我想接收外部数组中数字最大的元素作为第一个元素。
我该怎么做?
谢谢。
您可以使用
PHP 的usort()
定义任何排序算法
usort($array, function($a, $b) {
return $a[0] > $b[0];
});
这将就地对数组进行排序,以便第一个元素具有最大的数字作为第一个元素。
没有必要(而且成本要高得多)对整个数组进行排序。这样的东西会起作用:
// 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
退房usort
: http://php.net/manual/en/function.usort.php
您必须编写自己的比较函数。