简体   繁体   中英

Store , Show and Delete items in session array

I am trying to save registered product id session in array, and delete any of the product from the session array using the id but it only save one and replace it when i post new product. I have searched online but still couldn't get what will help me fix this.

<?php 
session_start();
//Saving session
if(!empty($_SESSION["items"])){
$_SESSION["items"] = array();
$_SESSION["items"][] = $_POST['product_id'];
}else{
$_SESSION["items"] = $_POST['product_id'];
}

//Get one session
echo $_SESSION["items"][$_POST['product_id']];

//Delete one session
unset($_SESSION["items"][$_POST['product_id']]);
?>

Example 2

<?php 
session_start();
$product_id = '300';
$itemID = 'C';
if (!isset($_SESSION['items'])) {
  $_SESSION['items'] = array();
  $_SESSION['items'][$itemID] = array('code' => $product_id);
}else{
    $_SESSION["items"][$itemID][] = $product_id;
}
echo $_SESSION["items"]['A']['code']; // This is not showing anything
var_dump($_SESSION["items"]); // below array is what i get
?>

array(3) { ["A"]=> array(1) { [0]=> string(3) "100" } ["B"]=> array(1) { [0]=> string(3) "200" } ["C"]=> array(1) { [0]=> string(3) "300" } } 

Please can anyone assist me on how i can get this right

When there is no items in your session, you save it in the $_SESSION['items']. While when there is one item in it, you create a new array to save it, and drop the old value, and save the new item in the new array.

So there is only one item or array with one item or none item in your session.

Just replace your if eles statement to this, to avoid of the warning you can add @ at the beging of the assignment, or test if its set before the assignment.

$_SESSION["items"][] = $_POST['product_id'];

Example Code:

$product_id = '300';
$itemID = 'C';
if (!isset($_SESSION['items'])) {
    $_SESSION['items']=[];
}
$_SESSION["items"][$itemID]['code']=$product_id;
var_export($_SESSION["items"]);

Output:

array (
  'C' => 
  array (
    'code' => '300',
  ),
)

Every added $product_id will have a key of code . That subarray will be inside of $itemID which will be inside of items which will be inside of $_SESSION .

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