我如何返回最大值的所有索引..例如,有一个包含学生成绩的数组
$grade = array(
"anna" => "5",
"lala"=>"7",
"eni"=>"7",
我想返回具有最高分的学生的姓名 在这种情况下应该打印:lala ENI
答案 0 :(得分:2)
您可以使用max()来查找最高值,然后对其执行array_keys()。
http://php.net/manual/en/function.max.php http://php.net/manual/en/function.array-keys.php E.g。
$grade = array(
"anna" => "5",
"lala"=>"7",
"eni"=>"7",
$max = max($grade); // $max == 7
array_keys($grade, $max);
答案 1 :(得分:1)
$maxInd = -1;
foreach($grade as $name => $ind) {
if($ind > $maxInd) {
$maxInd = $ind;
$maxRes = array();
}
if($ind == $maxInd) {
$maxRes[] = $name;
}
}
return "The highest names are " . implode(', ',$maxRes);
请告诉我它是否有效!
答案 2 :(得分:0)
$inversed = Array();
$highGrade = 0;
foreach ($grade AS $student=>$grade){
if (isset($inversed[$grade]))
$inversed[$grade][] = $student;
else
$inversed[$grade] = Array($student);
if ($grade > $highGrade) $highGrade = $grade;
}
print_r($inversed[$highGrade]);
答案 3 :(得分:0)
<?php
$grade = array(
"atest" => 6,
"banna" => "5",
"lala"=>"7",
"eni"=>"7");
asort($grade);
$reverse = array_reverse($grade);
$prev_val='';
$counter = 0;
foreach($reverse as $key=>$value)
{
if((($counter==1)&&($value==$prev_val))||($counter==0))
{
echo $key."->".$value."<br/>";
$prev_val = $value;
$counter++;
}
}
?>
我在数组中添加了一个元素以清除您的怀疑。