Php 如何在特定条件下提取数组中的最高值和最低值?
假设我在数组中有以下情况:Php 如何在特定条件下提取数组中的最高值和最低值?,php,Php,假设我在数组中有以下情况: [0] => 4 - 0 [1] => 0 - 1 [2] => 2 - 2 [3] => 1 - 2 [4] => 0 - 0 该值被组织为主队队的第一列,以及客场队的最后一列,因此主队以4-0赢得第一行 现在,我试图提取“最佳胜利”,在这种情况下是4-0,以及“最大失败”,即0-1 我现在尝试的是迭代数组索引: $biggestVictory = array_fill(0, 2, 0); $biggestDefeat = array
[0] => 4 - 0
[1] => 0 - 1
[2] => 2 - 2
[3] => 1 - 2
[4] => 0 - 0
该值被组织为主队
队的第一列,以及客场
队的最后一列,因此主队以4-0
赢得第一行
现在,我试图提取“最佳胜利”,在这种情况下是4-0
,以及“最大失败”,即0-1
我现在尝试的是迭代数组索引:
$biggestVictory = array_fill(0, 2, 0);
$biggestDefeat = array_fill(0, 2, 0);
foreach ($results as $result)
{
$score = explode("-", $result);
$home = $score[0];
$away = $score[1];
if($home > $biggestVictory[0] && $away <= $biggestVictory[1])
{
$biggestVictory[0] = $home;
$biggestVictory[1] = $away;
}
if($away > $biggestDefeat [1] && $home <= $biggestDefeat [0])
{
$biggestDefeat [1] = $home;
$biggestDefeat [2] = $away;
}
}
$biggestVictory=数组填充(0,2,0);
$BIGGESTFILT=数组填充(0,2,0);
foreach($results作为$result)
{
$score=分解(“-”,$result);
$home=$score[0];
$away=$score[1];
如果($home>$BIGGESTVICTION[0]&&&$WAY$BIGGESTVICTION[1]&&&&$home我有点不清楚“最大的胜利”到底应该是什么。得分的最大差异,或者得分的大多数目标?假设差异是重要的,下面的代码应该起作用:
$biggestVictory = array_fill(0, 2, 0);
$biggestDefeat = array_fill(0, 2, 0);
foreach ($results as $result)
{
$score = explode("-", $result);
$home = $score[0];
$away = $score[1];
if( ($home - $away) >= ($biggestVictory[0] - $biggestVictory[1]) )
{
$biggestVictory[0] = $home;
$biggestVictory[1] = $away;
}
if( ($away - $home) >= ($biggestDefeat[1] - $biggestDefeat[0]) )
{
$biggestDefeat [0] = $home;
$biggestDefeat [1] = $away;
//look at the index ^ you had a mistake in here
}
}
请注意,您的条件如果($home>$biggestVictory[0]&&&$away您可以使用Max函数来查找数组中的最大值
函数的作用是:返回数组中的最大值或
多个指定值的值
您还可以使用mini函数查找数组中的最小值
函数的作用是:返回数组中的最小值或
多个指定值的值
0-1
和1-2
的得分差异相同。为什么1-2
比0-1
更大的失败?你对“最大胜利”和“最大失败”的定义是什么?那么你的“最大胜利”是什么胜利的最大差距是什么?3-0的胜利会比4-2的胜利更大吗?这样的游戏不需要存在。如果你有5-1和1-0,它们都不符合你的要求。($biggestVictory[0]-$biggestVictory[0])
将始终为0
。您是想使用不同的索引吗?谢谢,是的,确实是一个输入错误。现在@Barmar已修复
<?php
echo(max(2,4,6,8,10) . "<br>");
echo(max(22,14,68,18,15) . "<br>");
echo(max(array(4,6,8,10)) . "<br>");
echo(max(array(44,16,81,12)));
?>
<?php
echo(min(2,4,6,8,10) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
echo(min(array(4,6,8,10)) . "<br>");
echo(min(array(44,16,81,12)));
?>