php unset after foreach

假如想象 提交于 2019-12-12 03:39:01

问题


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:


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.



来源:https://stackoverflow.com/questions/43896004/php-unset-after-foreach

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!