Update value in session array php

前端 未结 3 1505
小鲜肉
小鲜肉 2021-01-07 14:33

I have question about the SESSION array.

I just add item and qty in different session. I use code like this :

$_SESSION[\'idproduct\'] = $id.\",\";         


        
相关标签:
3条回答
  • 2021-01-07 14:52

    Store them as arrays, that way you can access the quantity using the ID as a key:

    $_SESSION['quantity'][$id] = $quantity;
    

    So instead of storing your ID and Quantity in two separate strings, you have them in one array, with the ID as the key. Converting your example above your array will look like this:

    array(
        1    => 3
        4    => 4
        6    => 5
    );
    

    Then if you wanted to add / adjust anything you just set $id and $quantity to the appropriate values and use the line above.

    0 讨论(0)
  • 2021-01-07 15:14

    The best way to achieve it is to store quantity as a value with product ID as a key, so if you have:

    idproduct  = 1,4,6,
    qtyproduct = 3,4,5,
    

    Store it as:

    $_SESSION['qtyproduct'] = array(
      1 => 3,
      4 => 4,
      6 => 5,
    );
    

    Right now if you have a product id:

    $id = 4;
    

    You can access quantity with:

    $quantity = $_SESSION['qtyproduct'][$id];
    

    and modify it with:

    $_SESSION['qtyproduct'][$id] = 7;
    
    0 讨论(0)
  • 2021-01-07 15:17

    You could use explode function and push another item into the array

    $items = explode($_SESSION['idproduct']);
    $items[] = $your_new_value;
    print_r($items); // this will you the values inside the array.
    $_SESSION['idproduct'] = implode(',', $items);
    
    0 讨论(0)
提交回复
热议问题