2013-09-24 29 views
0

我有一個像下面一樣的嵌套數組。當用戶提交時更新總價格陣列

cart ( 
[total] => 98 
[itemcount] => 3 
[items] => Array ([0] => 0 [1] => 3 [2] => 5) 
[itemprices] => Array ([0] => 33.00 [3] => 32.00 [5] => 33) 
[itemqtys] => Array ([0] => 1 [3] => 1 [5] => 1) 
[iteminfo] => Array ([0] => Chemistry [3] => Additional Mathematics [5] => Physics) 
) 

而且我在當用戶輸入正確的優惠碼開關下面的代碼,此功能將被觸發。我可以讓它工作來顯示折扣價格。

$anewvalue = 16.50; 
$physubject = "Physics"; 
$index = array_search($physubject , $cart->iteminfo); 
if (false !== $index) { 
$cart->itemprices[$index] = $anewvalue;} 

問題是,我該如何更新總每當一個正確的折扣代碼的用戶密鑰並提交表單,從而使總價格將總是最新的,因爲現在沒有做到這一點。

+0

您需要在某處存儲該值。平面文件,數據庫等 – andrewb

+0

@andrewb我可以將它存儲在會話中嗎? –

+0

用戶會話?當用戶註銷/離開時將被破壞。解釋你的要求。 – andrewb

回答

0

您需要在每次應用正確的折扣時重新計算總計。

if (false !== $index) { 
    $cart->itemprices[$index] = $anewvalue; 
    //re-calculate the total 
    $total = 0; 
    foreach ($cart->itemprices as $key=>$itemprice) { 
     $total += $itemprice * $cart->itemqtys[$key]; 
    } 
    $cart->total = $total 
} 
+0

謝謝!它的工作原理,但我需要把每個人的foreach放在開關盒裏嗎? –

+0

我不是那麼確定,你是如何實現你的開關盒,但我假設你使用開關盒的每個不同的折扣。如果是這種情況,則可以在所有開關盒完成後實際應用總重新計算。 – Vincent

+0

好吧,明白了。多謝兄弟。 –

相關問題