PHP两个相等的最大值

时间:2018-07-03 14:13:43

标签: php

我有一些PHP,我想根据数组的最大结果来更改变量。我需要它来设置一条消息,如果最大值附近有平局,我就快到了(除了有平局之外,结果返回正确的值)

任何帮助表示赞赏:)

$ex_res = ($ex1+$ex2)/2;
$ag_res = ($ag1+$ag2)/2;
$con_res = ($con1+$con2)/2;
$em_res = ($em1+$em2)/2;
$op_res = ($op1+$op2)/2;


$highest = max($ex_res ,$ag_res, $con_res, $em_res, $op_res);
if ($highest == $ex_res) {$dom_trait = "EXTROVERSION";}else
if ($highest == $ag_res) {$dom_trait = "AGREEABLENESS";}else
if ($highest == $con_res) {$dom_trait = "CONSCIENTIOUSNESS";}else
if ($highest == $em_res) {$dom_trait = "EMOTIONAL";}else
if ($highest == $op_res) {$dom_trait = "OPENNESS";}else { 
$dom_trait="NONE";
}

1 个答案:

答案 0 :(得分:2)

这就是您的价值:

$ex_res = ($ex1+$ex2)/2;
$ag_res = ($ag1+$ag2)/2;
$con_res = ($con1+$con2)/2;
$em_res = ($em1+$em2)/2;
$op_res = ($op1+$op2)/2;

要知道是否有平局,您可以构建一个数组并使用array_count_value()检查是否多次出现相同的值:

$array = array($ex_res, $ag_res, $con_res, $em_res, $op_res);

例如,假设您有$array = array(10, 20, 20, 15, 18);

$array_count_value = array_count_values($array);

输出为:

array (size=4)
    10 => int 1
    20 => int 2
    15 => int 1
    18 => int 1

现在只需执行您已经做的事情即可获得$hightest值:

$highest = max($ex_res ,$ag_res, $con_res, $em_res, $op_res);

因此,在我的示例中,您有:

$highest = max(10, 20, 20, 15, 18);
$highest = 20;

要知道是否有平局,只需检查一下您是否有一个值> 1:

foreach ($array_count_value as $result => $count) {
    if ($count > 1 && $result === $highest) {
        echo "Tie for highest value " . $result;
    }
}

编辑:也可以按照评论中的建议进行操作:

if ($array_count_value[$highest] > 1)
    echo "Tie for highest value " . $highest;

在我的示例中,输出为:Tie for highest value 20

是您要找的东西吗?