php unset after foreach

2019-09-11 15:10发布

I have a kind of store where members of a ski club can rent equipment. The first step is a loop where the member can make repetitive choices, for example for him and his family. Each line of material has its own total with a grand total at the bottom. A problem occurs once the last renting has been done and the member want to finalize his payment. The line of the last rented equipment is doubled and as a result the grand total is false. An idea how to solve this. I think it has something to do with my UNSET instruction. Thanks for helping. Here is the code of my foreach loops:

foreach ($price as $key => $value) {
   $number[$key] = str_pad($number[$key], 2);
   $type[$key] = str_pad($type[$key], 21);
   $lenght[$key] = str_pad($lenght[$key], 15);
   $boots[$key] = str_pad($boots[$key], 22);
   $size[$key] = str_pad($size[$key], 15);
   $priceskipers[$key] = ($priceski[$key]) * ($person[$key]);
   $pricebootspers[$key] = ($priceboots[$key]) * ($person[$key]);
   $total[$key] = array_sum(array($priceskipers[$key], $pricebootspers[$key]));
   $supertotal = 0;  
   $id++;
   echo "<pre>Data : " .$date[$key] . " | " . $number[$key] . " / " . $person[$key] . "| " . $type[$key] . " | " . $lenght[$key] . " | " . $boots[$key] . " | " . $size[$key] . "<br> " . $priceskipers[$key] . " + " . $pricebootspers[$key] . "  =  " . $total[$key] . " for this reservation (id" . $id . ").<hr></pre>";    
      unset($value);
      foreach ($total as $key2 => $value2) {
   $supertotal += $total[$key2];  
   $discount = (($supertotal) * 0.2);
   $grandtotal = (($supertotal) - ($discount));
  }
  }
   echo "<pre><b>Total " . $supertotal . " - 20% (discount for online renting) " . $discount . " = " . $grandtotal . ", your net amount.</b></pre>";

1条回答
聊天终结者
2楼-- · 2019-09-11 16:09

First of all, better you should provide fully each of your real input variables so that community can simulate easier.

Even the code above was not a proper way but it still works. No point for the unset() call to go here.

Next, a bit refactor, move the last foreach block out of the main loop: #1

foreach ($price as $key => $value) {
    //old logic
}

foreach ($total as $key2 => $value2) {
    $supertotal += $total[$key2];
    $discount = (($supertotal) * 0.2);
    $grandtotal = (($supertotal) - ($discount));
}

Next, you can even remove the whole calculation in foreach loop of #1 by:

$superTotal = array_sum($total);
$discount = $superTotal * 0.2;
$grandTotal = $superTotal - $discount;

Last, your comment is about when after all user click on pay button then things get broken, it means the calculation then totally depend on how the event after click on pay button.

查看更多
登录 后发表回答