将值应用于foreach循环PHP中的值

时间:2015-09-25 07:02:04

标签: php

我正在寻找一个解决方案,根据项目的foreach循环对某个值应用折扣,我的主要问题是,如果第二个项目符合要求它也适用于它,那么我想要什么只是应用于已找到需求的第一个项目,然后传递给其他操作。

    echo '<pre>';

        $requeriment = 299;
        $items = array(
                        array(
                            'id' => 1,
                            'price' => 199,
                            'quantity' => 1
                        ),
                        array(
                            'id' => 2,
                            'price' => 399,
                            'quantity' => 1
                        ),
                        array(
                            'id' => 3,
                            'price' => 199,
                            'quantity' => 1
                        )
        );

        $flag = false;

        foreach($items as $item){
            $totalItem = $item['price'] * $item['quantity'];
            if($totalItem > $requeriment){
                if(!$flag){
                    $flag = true;
                    echo 'Disc 1% - ' . $item['id'];
                    echo "<br>";
                }else if($flag){
                    echo 'Disc 2% - ' . $item['id'];
                    echo "<br>";
                }
                continue;
            }
            echo 'Disc 2% - ' . $item['id'];
            echo "<br>";
        }
    //Ok, it found ID 2 with a value bigger than requirement and the job is done.

//Now if trough loop it not found item that meet the requirement 
//it need now to sum values to get the required value to meet the requirement
//and apply a 1% the the 2 items that made that sum, then apply 2% to the rest of ids.

在同一个循环中有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

  $i=0;
  foreach $items as $item{
   $i++;
  $totalItem = $item->price * $item->quantity;
if($totalItem > $requeriment){

//Apply a discount of 1%
    if($i==1){

     // for discount 1
    }elseif($i==2){
          // for discount 2
       }
  }

和其他折扣一样。