i'm struggling with some shopping cart exercise... I would like to have one function which takes care of all my adding items logic.
When selecting an item, it should add it to my cart. If there is no item yet in the cart, it should be added with amount 1. After adding the same item again, it should increase the amount.
What i have up to now looks like this:
public function addToCart($id){
$this->articleName = ($this->getArticleNamefromID($id)[0]["name"]);
if ($_SESSION['cart'] == null){
$array = ["articleName" => $this->articleName, "amount" => 1];
array_push($_SESSION['cart'], $array);
}else{
foreach($_SESSION['cart'] as $key => $value) {
if($value["articleName"] != $this->articleName){
$array = ["articleName" => $this->articleName, "amount" => 1];
array_push($_SESSION['cart'], $array);
}else {
$amountInc = $value["amount"] + 1;
$_SESSION['cart'][$key]["amount"] = $amountInc;
}
}
}
}
The first item will be add up as expected (in this case daycream), when i try to insert a new item (nightcream), it will stack up like this instead of counting up the amount:
Cart:
Array
(
[0] => Array
(
[articleName] => Daycream
[amount] => 10
)
[1] => Array
(
[articleName] => Nightcream
[amount] => 6
)
[2] => Array
(
[articleName] => Nightcream
[amount] => 5
)
[3] => Array
(
[articleName] => Nightcream
[amount] => 4
)
[4] => Array
(
[articleName] => Nightcream
[amount] => 3
)
[5] => Array
(
[articleName] => Nightcream
[amount] => 2
)
[6] => Array
(
[articleName] => Nightcream
[amount] => 1
)
)
$this->articleName is a sql call to the db and gives me always the selected item, this should be ok. I guess I have some issues with foreach($value["articleName"] != $this->articleName)
My intend was to check if the current value from cart matches the given articleName, if so count amount + 1 or add a new item into the cart.
Can you maybe help me?
Thx in advance!
EDIT1 added array_filter for getting current articleName
public function addToCart($id){
$this->articleName = ($this->getArticleNamefromID($id)[0]["name"]);
if ($_SESSION['cart'] == null){
$array = ["articleName" => $this->articleName, "amount" => 1];
array_push($_SESSION['cart'], $array);
}else{
foreach($_SESSION['cart'] as $key => $value) {
$currentItem = array_filter(
$_SESSION['cart'], function ($e) use (&$searchedValue) {
return $e->articleName == $searchedValue;
}
);
//Check values
echo $this->articleName. " vs. " . $currentItem;
if($currentItem == $this->articleName){
$amountInc = $value["amount"] + 1;
$_SESSION['cart'][$key]["amount"] = $amountInc;
}else {
$array = ["articleName" => $this->articleName, "amount" => 1];
array_push($_SESSION['cart'], $array);
}
}
}
}