php - 如何计算数组值和键,直到达到目标

时间:2016-11-22 14:47:23

标签: php arrays

我有一系列值,我需要计算它们,但直到达到$ target数量。我需要知道达到目标需要多少个数组键($ count)以及相应值的总和($ total)。这是我使用的数组:

$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,而$ count应为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";

4 个答案:

答案 0 :(得分:2)

$target = 9;
$total = 0;

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

    $total += $value;
}

echo "total is $total and count is $key";

答案 1 :(得分:0)

将$ outgoing重命名为$ 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

的未使用的循环条目

答案 2 :(得分:0)

如果密钥相等且大于$key中断foreach循环,您可以检查$target。像这样的东西 -

<?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)的

答案 3 :(得分:-1)

添加if语句

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

你不需要while循环。