如果条件为真,则PHP foreach重置并删除/减去数组值

时间:2016-06-10 06:32:20

标签: php arrays foreach

如果我有以下值,$ result = 0,$ request = 50和$ array = [25,20],我如何重置和减去$ request value to 如果$ request值大于$ array,则为$ array。如果情况如此,foreach将会破裂 $ request小于$数组值,$ request = 0或$ array values = 0.

这样的情况和$ result将是5。

50      -    [25, 20]
|___   >=   __|    |
   25      00      |
   |_  >=  ________|
     5    00

的代码:

while(true) {
    $reset    = false
    $result   = 0;
    foreach($array as $key => $value) {
        if($request >= $value) {
            ....
        } else {
            ....
            $reset = true;
            break;
        }
    }

    if(!$reset) {
        break;
    }
}

2 个答案:

答案 0 :(得分:1)

$request将与$result相同,因此它是相同的,因此不需要。

$request = 50;
$array = array(25, 20);

foreach($array as $key => $value) {
    if($request < $value || $request === 0 ) {
      break;
    }

    $request = $request - $value;
}

echo 'Result: '.$request;

<强> TESTS

$request = 50;

$array = array(25, 20); 
// Result: 5

$array = array(25, 30); 
// Result: 25

$array = array(25, 25); 
// Result: 0

$array = array(51, 10);
// Result: 50

修改

根据评论和OP小提琴进行编辑。

$request = 50;
$array   = array(20, 25, 25);
$excess = max(array_sum($array) - $request, 0);

foreach($array as $key => $value) {
    if($request < $value || $request === 0 ) {
      $request = 0;
      break;
    }

    $request = $request - $value;
}


echo 'Result: '.$request.'<br />';
echo 'excessValue: '.$excess;

<强> TESTS

$request = 50;

$array  = array(25, 20);
// Result: 5, excess: 0

$array = array(50, 20);
// Result: 0, excess: 20

$array   = array(52, 5);
// Result: 0, excess: 7

$array   = array(20, 25, 25);
// Result: 0, excess: 20

答案 1 :(得分:0)

<?php 
while(true) {
    $reset    = false;
    $result   = 0;
$request = 51;
$array = array(25, 20); 

foreach($array as  $value) {
    if($request>=$value){
        $request=$request-$value;
    }
    else{
    break;
            }
echo 'Result: '.$request;
    }
    if(!$reset) {
        break;
    }
}
?>