I would like to make multidimensional array but after looking on it for hours I am quite lost. I am sending ID and quantity from modal via AJAX, and I want to store it like this $_SESSION['cart'] =>array(here should be IDs => and each ID is pointing to its quantity)
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array(array());
}
if(isset($_REQUEST['id'])){
$_SESSION['cart'][] = $_REQUEST['id'];
$_SESSION['cart'][][] = $_REQUEST['quantity'];
}
I am trying to access it like that:
foreach($_SESSION['cart'] as $value){
//var_dump($value);
//echo "<br>";
foreach($value as $item){
var_dump($item);
echo "<br>";
}
}
But for second foreach I get warning that its argument is invalid, which I can bypass with converting the $value to array. Is this the right way to do it ? or is there any better ? Thanks
Type these in your address bar:
/path/to/your/file.php?id=10&quantity=20
/path/to/your/file.php?id=11&quantity=30
/path/to/your/file.php?id=12&quantity=15
/path/to/your/file.php?id=10&quantity=80
file.php
session_start();
if(!isset($_SESSION['cart'])){
$_SESSION['cart']=array();
}
if(isset($_REQUEST['id'])){
foreach ($_SESSION['cart'] as $index => $item) {
if ( array_key_exists($_REQUEST['id'],$item) ) {
$_SESSION['cart'][$index][$_REQUEST['id']] = $_REQUEST['quantity'];
$flag=1;
break;
}
}
if ($flag==0) {
$_SESSION['cart'][] = array($_REQUEST['id'] => $_REQUEST['quantity']);
}
}
foreach ($_SESSION['cart'] as $index => $item) {
foreach ($item as $id => $quantity) {
echo 'id is :'.$id.', quantity is:'.$quantity.'<br>';
}
}
Result:
id is :10, quantity is:80(20 previous)
id is :11, quantity is:30
id is :12, quantity is:15
What this line is supposed to to ?
$_SESSION['cart'][][] = $_REQUEST['quantity'];
You'd better write:
if(isset($_REQUEST['id'])){
$_SESSION['cart'][$_REQUEST['id']] = $_REQUEST['quantity'];
}
Explanation
To add a key
=> value
to an array
, you have to write:
array[key] = value
Here your array is $_SESSION['cart']
, your key is $_REQUEST['id']
, and your value is $_REQUEST['quantity']
. So you have to write:
$_SESSION['cart'][$_REQUEST['id']] = $_REQUEST['quantity'];
Or, step by step...
$array = $_SESSION['cart'];
$id = $_REQUEST['id'];
$value = $_REQUEST['quantity'] ;
$array[$key] = $value ;
$_SESSION['cart'] = $array ;
To access it:
foreach($_SESSION['cart'] as $key => $value){
echo "For key $key, value is $value" . "<br>" ;
}