Reputation: 103
I want to implement the shopping cart by using multidimensional session array but don't know how to access them. For example,
line1: pname"x" size"m" quantity"2"
How can I manipulate it as 2 line of order?
line1: pname"x" size"m" quantity"1"
line2: pname"x" size"s" quantity"1"
if (!isset($_SESSION['order'])) {
$_SESSION['order'] = array();
}
$_SESSION['order'][] = array('id'=>$pID, 'size'=>$size, 'quantity'=>0);
switch ($action) {
case "add":
$_SESSION['order'][]['quantity']++;
break;
case "remove":
unset($_SESSION['order'][][$pID]);
break;
case "empty":
unset($_SESSSION['order']);
break;
}
Upvotes: 0
Views: 646
Reputation: 1634
i would suggest you to use objects instead of array for this. Using arrays will create a kind of complication and make your code less readable and more complex; I would suggest you to use an object oriented approach.
just create two classes:
class ShoppingCart {
private $items;
public function getItems(){
return $this->items;
}
public function addItem($item){
$this->items[] = $item;
}
class Item {
private $name;
private $size;
public function getName() { return $this->name;}
public function getSize() { return $this->siez; }
public function setName($name) { $this->name = $name; }
public function setSize($size) { $this->size = $size; }
Now you can add items to the cart like this:
$cart = new ShoppingCart();
$item1 = new Item();
$item1->setName('x');
$item1->setSize('m');
$item2 = new Item();
$item2->setName('x');
$item2->setSize('s');
$cart->addItem($item1);
$cart->addItem($item2);
Did you see, this code is readable and can be easy understood.
Upvotes: 0
Reputation: 39704
Your session will get an element every time you call []
. Add $pID
as variable id:
Change to:
if (!isset($_SESSION['order'])) {
$_SESSION['order'] = array();
}
$_SESSION['order'][$pID.'-'.$size] = array('quantity'=>0);
switch ($action) {
case "add":
$_SESSION['order'][$pID.'-'.$size]['quantity']++;
break;
case "remove":
unset($_SESSION['order'][$pID.'-'.$size]);
break;
case "empty":
// unset($_SESSION['cart']);
unset($_SESSSION['order']);
break;
}
You can later access that product with $_SESSION['order'][$pID.'-'.$size]
To access them:
foreach($_SESSION['order'] as $key => $one){
list($pid, $size) = explode('-', $key);
}
Upvotes: 1