我知道如何在PHP中找到最大值
$max = max($var);
但是当它具有多个最大值时,它只显示了一个值。但我怎么能获得多个价值?
示例:(7,5,8,8,4,7,6)
如何让'8'显示?
答案 0 :(得分:3)
您可以像{/ p>一样使用array_filter
$arr = [7,5,8,8,4,7,6];
$max = max($arr);
$result = array_filter($arr,function($v)use($max){ return $v == $max;});
print_r($result);
<强>输出强>
Array
(
[2] => 8
[3] => 8
)
答案 1 :(得分:0)
如果您不关心项目的索引,那么这将起作用:
$biggest = max($var);
$totalOfEach = array_count_values($var);
$totalBiggest = $totalOfEach[$biggest];
$arrayOfBiggest = array_fill(0, $totalBiggest, $biggest);
如果你关心项目的索引,那么你需要过滤而不是重建数组:
$biggest = max($var);
$filter = function ($value) use ($biggest) { return $biggest === $value; };
$filteredArray = array_filter($var, $filter);
你可以选择第二个作为更少的代码但是...它涉及迭代每个var项目,这可能是昂贵的。
答案 2 :(得分:0)
试试这个:
<?php
$arr=array(7,5,8,8,4,7,6);
$str=getMultipleMax($arr);
echo rtrim($str, ',');
function getMultipleMax($arr){
$max=$arr[0];
$maxstr=array();
foreach($arr as $values){
if($values > $max){
$max=$values;
$maxstr ="";
$maxstr .=$values.",";
}else if($values == $max){
$maxstr .=$values.",";
}
}
return $maxstr;
}
答案 3 :(得分:0)
尝试使用array_count_values,例如:
<?php
$input = [7,5,8,8,4,7,6];
$countValues = array_count_values($input);
$max = max($input);
print('Max: ' . $max) . PHP_EOL;
print('count[max]:' . $countValues[$max]) . PHP_EOL;
print_r($countValues);
答案 4 :(得分:-1)
为什么不先列出sort列表,然后使用array_pop
获取下一个最大值:
$results = array(7,5,8,8,4,7,6);
sort($results);
$first = array_pop($results);
$second = array_pop($results);
答案 5 :(得分:-1)
这是我的设备代码。
描述:当最大值超过一个
时打印多重结果<?php
$test=8; //Var
$results = array(7,5,8,$test,8,4,7,6); //Array
sort($results); //Sort
if(max($results)==$test){ //If Max equal to '8'
echo " You're Engineer ";
$first = array_pop($results);
if(max($results)==$first){//If I have another '8'
echo " or ";
echo " You're Programmer ";
$second = array_pop($results);
if(max($results)==$second){ //If I have another '8' again
echo " or ";
echo " Scientist ";}
}
}
?>