我正在寻找一种解决方案,将折扣应用到基于项目的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.
是否有办法在同一循环中做到这一点?
$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
}
}
与其他折扣相同