I am trying to check if a value exists in an array and don't add an entire new entry to it, but instead only add to the quantity in the existing data.
My array looks like this:
Array
(
[0] => Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] => 20
)
[1] => Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] => => 18
)
)
So to check if a value exists I did the following:
if(in_array('Douche 1', array_column($_SESSION['cart'], 'product'))) { // search value in the array
echo "FOUND";
}
But instead of echoeing FOUND, I need the array to merge in a way, all stays the same, only the quantity needs to add up.
So when my array is like this:
Array
(
[0] => Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] => 20
)
)
And I add a product with 15 quantity, I want the array to change to this:
Array
(
[0] => Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] => 35
)
)
So the quantity adds up only when a productname is added that already exists, if it doesn't exist, there just needs to be a new key (with an array in it).
How can I do that?
My entire array code (excluding ajax and my loop) at the moment is this:
if(isset($_POST['product'])){
$thisProduct = array(
'product' => $_POST['product'],
'price' => $_POST['price'],
'picture' => $_POST['picture'],
'quantity' => $_POST['quantity'],
);
if (isset($_SESSION['cart'])) {
$_SESSION['cart'][] = $thisProduct;
} else {
//Session is not set, setting session now
$_SESSION['cart'] = array();
$_SESSION['cart'][] = $thisProduct;
}
}
if(in_array('Douche 1', array_column($_SESSION['cart'], 'product'))) { // search value in the array
echo "FOUND";
}