Jump to content

Problem Reducing Shopping Basket Quantity By 1


stevesimo

Recommended Posts

Hi, I am trying to use some code which I have found in a tutorial to write my first shopping cart in PHP.

 

The code has an example to delete an item from the basket or to add an item to the basket.  However the code doesnt explain how to reduce a quantity in basket by 1.

 

Here is the code to delete an item from the basket

 

if ($cart) {

  $items = explode(',',$cart);

  $newcart = '';

  foreach ($items as $item) {

    if ($_GET['id'] != $item) {

      if ($newcart != '') {

        $newcart .= ','.$item;

      } else {

        $newcart = $item;

      }

    }

  }

$cart = $newcart;

}

 

Can anyone see what I need to do to reduce the quantity by 1.  Also How would I prevent the problem of somebody trying to reduce a quantity if it is already 0?

Hi, I have discovered that the cart contains a comma seperated list of product ids.  So for example the cart 1,2,3,1,1,2 contains 3 of product 1, 2 of product 2, and 1 of product 3.  Providing I know what the product id is and that the quantity is greater than 0, how would I reduce the string by 1?

Fixed it using a long winded approach.

 

//do a count of all items in the trolley

  if ($cart){

    $items = explode(',',$cart);

    $contents = array();

    foreach ($items as $item) {

      $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;

    }

  }

  //initialise empty cart

  $tempcart = "";

  //for each product in list

  foreach ($contents as $id=>$qty){

  //is product in list equal to one being reduced

  if($id == $_GET['id'] && $qty > 0){

    for($i=1;$i<$qty;$i++)

      //add all items - 1

      $tempcart = $tempcart.$id.',';

    }else{

      for($i=1;$i<=$qty;$i++)

      //add all items

      $tempcart = $tempcart.$id.',';

  }

  //trim final comma

  $cartlength = strlen($tempcart) - 1;

  $tempcart = substr($tempcart,0,$cartlength);

}

//set cart to tempcart

$cart = $tempcart;

 

Thanks for your help

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.