开发者

shopping cart using $_session and send product name and quantity how can I send total cost at same time

below is the code am using to send product name and quantity, this works perfect I want to send a total cost at the same time that name and quantity get sent but am not sure how to go about doing this as am pretty new to php so thanks in advance

<?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 = arra开发者_C百科y_unique(array_merge($_SESSION['products'], $order));
    }
    $_SESSION['products'] = $order; 
  }


I've taken a very quick and slightly messy stab at it here. Fundamentally I disagree with the way you're doing things, you should really be thinking about using a more OO approach - but for the sake of getting things done, this should solve your problem and provide a bit more flexibility in future.

Oh and, check this out when you get a chance: http://php.net/manual/en/function.array-unique.php

Your array_unique(array_merge... code would have merged all products that had the same quantity and you would have lost products from the array. :)

Any questions, fire them over.

// 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜