Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: array values lost after for each
    primarykey
    data
    text
    <p>first let me explain what I am trying to achieve:</p> <p>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.</p> <p>I got really close with the help of this post: <a href="https://stackoverflow.com/questions/9240251/checking-if-array-value-exists-in-a-php-multidimensional-array?rq=1">Checking if array value exists in a PHP multidimensional array</a> </p> <p>this is the code I am using right now:</p> <pre><code> $item_id = arg(1); $quantity = '1'; $found = false; $bought_items = null; $data = null; foreach ($user_items as $key =&gt; $data) { if ($data['a'] == $item_id) { // The item has been found =&gt; 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 =&gt; exit the loop } } if ($found === false) { $bought_items = array('a' =&gt; $item_id, 'b' =&gt; $quantity); } $array = array($bought_items, $data); </code></pre> <p>If the item_id is non existing, it is added to the array If the item_id is existing, the quantity will 'receive' +1</p> <p>so far so good</p> <p><strong>now the actual problem, let's sketch the scenario:</strong></p> <p>I purchase item 500 -> array contains: id=500, quantity=1</p> <p>I purchase item 500 -> array contains: id=500, quantity=2</p> <p>I purchase item 600 -> array contains: id=500, quantity=2, id=600, quantity=1</p> <p><strong>after this it goes wrong</strong></p> <p>I then purchase item 500 <strong>or</strong> 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.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload