![](/img/trans.png)
[英]how can i write an algorithm to multiply the total * quantity in a shopping cart using php $_SESSION?
[英]shopping cart using $_session and send product name and quantity how can I send total cost at same time
下面是用於發送產品名稱和數量的代碼,這很完美,我想在發送名稱和數量的同時發送總成本,但是不確定如何進行此操作,因為這對php來說還很新提前致謝
<?php
if (isset($_POST['form_products'])) {
$quantity=$_POST['quantity'];
$total = $the_price_is * $quantity; // want to be able to send $total at same time
$order = array($_POST['dryer']=>$_POST['quantity']);
if (!empty($_SESSION['products'])) {
foreach($_SESSION['products'] as $name => $quantity_value){
if (isset($order[$name])){
print "<br>Your order as been added to your cart";
$order[$name]+=$quantity_value;
}
}
$order = array_unique(array_merge($_SESSION['products'], $order));
}
$_SESSION['products'] = $order;
}
我在這里采取了一個非常快速且有點混亂的方法。 從根本上來說,我不同意您的處事方式,您應該真正考慮使用一種面向對象的方法-但是為了使事情做好,這應該可以解決您的問題並在將來提供更多的靈活性。
哦,有機會請檢查一下: http : //php.net/manual/en/function.array-unique.php
您的array_unique(array_merge ...代碼將合並所有具有相同數量的產品,並且您將從陣列中丟失產品。:)
如有任何疑問,請將其解雇。
// im assuming you've called this somewhere already:
// session_start();
// store the initial details
$quantity = $_POST['quantity'];
$total = $the_price_is * $quantity; // want to be able to send $total at same time
// build multi-dimensional order array
$order = array(
$_POST['dryer'] => array('quantity' => $_POST['quantity'], 'total' => $total)
);
// merge any session products into the order array if necessary
if (isset($_SESSION['products']) && is_array($_SESSION['products']) ) foreach ($_SESSION['products'] as $name => $details) {
// add quantity and total if the 'product' is already in the session
if (isset($order[$name])) {
$order[$name]['quantity'] += $details['quantity'];
$order[$name]['total'] += $details['total'];
} else $order[$name] = $details;
}
// replace session products with newly built order array
$_SESSION['products'] = $order;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.