如何计算数组值和键,直到达到目标为止



我有一个值数组,我需要对它们进行计数,但只有直到达到$目标数量为止。我需要知道需要多少个数组键才能达到目标($计数)和这些相应值的总和(总计$)。这是我正在使用的数组:

$numbers = Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 6 [5] => 1 [6] => 5.5 [7] => 1 [8] => 1 [9] => 1 [10] => 1 [11] => 1 [12] => 1 [13] => 11 )

使用$target=9$total应为10,$计数应为5,但是我得到$total=9$count=9,因为代码似乎计数键而不是值。同样,如果目标为12,则$total应为16.5,$count应该是7,但我得到12和12。

希望一切都有意义。如果某人可以编辑此代码,以便它适用于任何数字数组,并且将不胜感激的任何目标。

$count=0;
$target=9;
$total=0;
foreach($numbers as $key => $value){
while($total < $target) {
$total = $total+$value;
$count++;
}
}
echo "total is $total and count is $count";
$target = 9;
$total = 0;
foreach($numbers as $key => $value) {
    if ($total >= $target) {
        break;
    }
    $total += $value;
}
echo "total is $total and count is $key";

如果键相等且大于 $target for foreach循环,则可以将检查您的$key放置。这样的东西 -

<?php
$numbers = Array ( 0 => 1, 1 => 1, 2 => 1, 3 => 1, 4 => 6, 5 => 1, 6 => 5.5, 7 => 1, 8 => 1, 9 => 1, 10 => 1, 11 => 1, 12 => 1, 13 => 11 );
$count=0;
$target=9;
$total=0;
foreach($numbers as $key => $value) {
  if ($key >= $target) {
    break;
  }
  $total += $value;
  $count++;
}
echo "total is $total and count is $count";
?>

希望这种结果成为您真正想要的。(y)。

重命名为$ target,然后更改为if

$count=0;
$target=9;
$total=0;
foreach($numbers as $key => $value){
    if($total < $target) {
        $total = $total+$value;
        $count++;
    }
    else
    {  
        break;
    }
}
echo "total is $total and count is $count";

upd:重写代码以避免使用Break

的未使用的循环条目

添加一个if语句

$total = 0;
foreach($numbers as $key => $value)
{
    $total = $total+$value;
    if($total >= $target)
    {
       $count = $key+1;
       break;
    }
}

您不需要while循环。

最新更新