简体   繁体   中英

PHP: access multidimensional session array

I want to implement the shopping cart by using multidimensional session array but don't know how to access them. For example,

  • case1: user add one item to the cart with name "x" and size"m". then add again with name "x" and size"m"

line1: pname"x" size"m" quantity"2"

  • case2: when user add one item to the cart with name "x" and size"m". then the user add another item to the cart with name "x" but size"s".

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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