我有三个值23,27,20。如何使用php从这些值中取出23和27?我已经搜索并分析了php内置的数组函数,它可以做到这一点,但是迷路了。请帮我。我是新手。
$p1=23;
$p2=27;
$p3=20;
$all=array($p1,$p2,$p3);
arsort($all);
$total=$all[1]+$all[2];
print "$total";// 23, 27 then sum up together 50.
答案 0 :(得分:1)
数组以索引0而不是1开头。 而不是
$total= $all[1] + $all[2];
你的加法逻辑是
$total= $all[0] + $all[1];
试试此代码
$p1=23;
$p2=27;
$p3=20;
$all=array($p1,$p2,$p3);
rsort($all);
echo $total= $all[0] + $all[1];
答案 1 :(得分:1)
由于您正在使用以相反顺序排序的asort
。
试试这个:
$p1=23;
$p2=27;
$p3=20;
$all=array($p1,$p2,$p3);
arsort($all); //Sort the array in reverse order.
$total=$all[0]+$all[1]; // get the first and the next values of the array.
// after the arsort they will be the higher values
print "$total";
答案 2 :(得分:1)
尝试使用rsort()
rsort($all);
$top2 = array_reverse(array_slice($all, 0, 2));// will find two highest values
print_r($top2) //Array ( [0] => 23 [1] => 27 )
echo $total= array_sum($top2);
或按键
echo $total= $top2[0] + $top2[1];
答案 3 :(得分:-2)
试试这个,
您将使用max(2,4,6,8,10)获得最高价值。
您将使用min(22,14,68,18,15)获得最高价值。
希望你明白了:)