views:

143

answers:

2

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.

+2  A: 

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.

timdev
A: 

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)
}
vito huang