简体   繁体   English

$ _session的购物车并发送产品名称和数量我如何同时发送总成本

[英]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来说还很新提前致谢

<?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; 
  }

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 哦,有机会请检查一下: 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. :) 您的array_unique(array_merge ...代码将合并所有具有相同数量的产品,并且您将从阵列中丢失产品。:)

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM