first let me explain what I am trying to achieve:
I've got an array of user items, consisting of an ID(item_id) and quantity(e.g. 10 items) If a user purchases an item, it's added to the array including the quantity. If a user purchases an (in the array) existing item, '1' is added to the quantity.
I got really close with the help of this post: Checking if array value exists in a PHP multidimensional array
this is the code I am using right now:
$item_id = arg(1);
$quantity = '1';
$found = false;
$bought_items = null;
$data = null;
foreach ($user_items as $key => $data) {
if ($data['a'] == $item_id) {
// The item has been found => add the new points to the existing ones
$data['b'] += 1;
$found = true;
break; // no need to loop anymore, as we have found the item => exit the loop
}
}
if ($found === false) {
$bought_items = array('a' => $item_id, 'b' => $quantity);
}
$array = array($bought_items, $data);
If the item_id is non existing, it is added to the array If the item_id is existing, the quantity will 'receive' +1
so far so good
now the actual problem, let's sketch the scenario:
I purchase item 500 -> array contains: id=500, quantity=1
I purchase item 500 -> array contains: id=500, quantity=2
I purchase item 600 -> array contains: id=500, quantity=2, id=600, quantity=1
after this it goes wrong
I then purchase item 500 or 600, the other item is removed from the array. So when I purchase item 500, item 600 and its quantities are removed from the array.
I've been puzzling for hours but can't find the mistake, I know I'm overlooking something logical. I think it's going wrong in the for each.