开发者

Multiple items in a PHP shopping cart

I'm in the progress of making a shopping cart in PHP. To check if a user has selected multiple products, I put everything in an array ($contents). When I output it, I get something like "14,14,14,11,10". I'd 开发者_运维知识库like to have something like "3 x 14, 1 x 11, 1 x 10". What is the easiest way to do that? I really have no clue how to do it.

This is the most important part of my code.

    $_SESSION["cart"] = $cart;

    if ( $cart ) {
        $items = explode(',', $cart);
        $contents = array();
        $i = 0;
        foreach ( $items as $item ) {
            $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
            $i++;
        }

        $smarty->assign("amount",$i);


        echo '<pre>';
        print_r($contents);
        echo '</pre>';

Thanks in advance.


Why not build a more robust cart implementation?

Consider starting with a data-structure like this:

$cart = array(
  'lines'=>array(
     array('product_id'=>14,'qty'=>2),
     array('product_id'=>25,'qty'=>1)
   )
);

Or similar.

Then you could create a set of functions that operate on the cart structure:

function addToCart($cart, $product_id, $qty){
   foreach($cart['lines'] as $line){
     if ($line['product_id'] === $product_id){
       $line['qty']  += $qty;
       return;
     }
   }
   $cart['lines'][] = array('product_id'=>product_id, 'qty'=>$qty);
   return;
}

Of course, you could (and perhaps should) go further and combine this data structure and functions into a set of classes. Shopping carts are a great place to start thining in an object-oriented way.


The built-in array_count_values function might does the job.

E.g:

<?php
$items = array(14,14,14,11,10);
var_dump(array_count_values($items));
?>

Outputs:

array(3) {
  [14]=>
  int(3)
  [11]=>
  int(1)
  [10]=>
  int(1)
}


You would benefit from using a multi dimensional array to store your data in a more robust structure.

For example:

$_SESSION['cart'] = array(
  'lines'=>array(
     array('product_id'=>14,'quantity'=>2, 'item_name'=>'Denim Jeans'),
     ...
   )
);

Then to add new items to the cart you can simply do this:

$_SESSION['cart'][] = array('product_id'=45,'quantity'=>1, 'item_name'=>'Jumper');


When you let a user add an item you need to add it in the right position in the array. If the product id already exist in the array, you need to update it. Also always be careful of users trying to enter zero or minus numbers!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜