I am posting some data in json format to a php script, this data needs to replace existing data that is in a session (array).
This is what I post to my PHP script:
Array
(
[0] => stdClass Object
(
[product] => Bad 1
[quantity] => 2
)
[1] => stdClass Object
(
[product] => Bad 14
[quantity] => 1
)
)
And this is my session array ($_SESSION['cart']
):
Array
(
[Bad 1] => Array
(
[artikelid] => 2
[product] => Bad 1
[price] => 1000
[picture] => cms/images/bad.jpg
[quantity] => 2
[alias] => bad1
[catalias] => baden
)
[Bad 14] => Array
(
[artikelid] => 11
[product] => Bad 14
[price] => 800
[picture] => images/defaultimage.jpg
[quantity] => 1
[alias] => bad-14
[catalias] => baden
)
)
I want the posted quantity value to replace the quantity value inside the session array, but only for the correct product ofcourse. So if I post quantity '10' with product 'bad 1' only the quantity of key 'bad 1' needs to be replaced with that value.
This also goes when posting multiple products like in my example (the posted object).
How can I change the object into an array and merge (replace quantity only) it with my session array?
Something similar I tried but this only works for one posted value.
//Wanneer er een post waarde is vanaf het ajax script:
if($_POST['product']){
//Stop de productnaam in de variabele $prod
$prod = $thisProduct['product'] ;
//Als er nog geen sessie bestaat, maak deze dan aan
if (!isset($_SESSION['cart'])) {
//en maak er gelijk een array van
$_SESSION['cart'] = [];
}
//Als de productnaam nog niet voorkomt in de sessie, voeg deze dan toe inclusief de overige array waarden
if (!isset($_SESSION['cart'][$prod])) {
$_SESSION['cart'][$prod] = $thisProduct;
}
//Als deze wel voorkomt voeg hem dan niet toe maar tel de quantity op bij het bestaande product
else {
$_SESSION['cart'][$prod]['quantity'] += $thisProduct['quantity'];
}
}
I fixed it like this with help from Don't Panic :
$quantityobject = $_POST['quantityobject'];
$arrayquantity = json_decode($quantityobject);
foreach ($arrayquantity as $object) {
// Check if product exists in array
if (isset($_SESSION['cart'][$object->product])) {
// if so replace quantity with posted one
$_SESSION['cart'][$object->product]['quantity'] = $object->quantity;
}
}