donglu3087 2016-06-10 06:32
浏览 95
已采纳

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

If I have following value, $result = 0, $request = 50 and $array = [25, 20], How do I reset and subtract $request value to $array values if $request value is greater than $array. and foreach will break if condition are $request less than $array value or, $request = 0 or, $array values = 0.

So condition like this and $result will be 5.

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

code:

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

    if(!$reset) {
        break;
    }
}
  • 写回答

2条回答 默认 最新

  • duanao2585 2016-06-10 07:10
    关注

    $request will be same as $result, so it's the same thing and therefore not needed.

    $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
    

    EDIT

    Edit based on comments and OP fiddle.

    $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条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)