For exemple I use this array:
Array (
[0] => Array ( [id] => 39584 [quantity] => 1 ) [1] => Array ( [id] => 39584 [quantity] => 3 ) [2] => Array ( [id] => 39574 [quantity] => 1 ) [3] => Array ( [id] => 39586 [quantity] => 1 ))
My question is: How can I update "quantity" if the "id" is similar to that introduced earlier?
Example:
Array (
[0] => Array ( [id] => 39584 [quantity] => 4 ) [1] => Array ( [id] => 39574 [quantity] => 1 ) [2] => Array ( [id] => 39586 [quantity] => 1 ))
Here is the solution:
$result = array();
foreach ($your_array as $sub_array) {
if (empty($result[$sub_array['id']])) {
$result[$sub_array['id']] = $sub_array;
} else {
$result[$sub_array['id']]['quantity'] += $sub_array['quantity'];
}
}
This will group arrays by their 'id' key and sum up values
If you need the array in this form you have to do a search.
foreach ($array as $set)
{
if ($set['id'] == $checkedId)
{
$set['quantity'] = $newQuantity;
return;
}
}
If you can change the array, why not make the id's the keys?
$newArray = array();
foreach ($oldArray as $set)
{
$newArray[$set['id']] = $set['quantity'];
}
Now you can access quantities with $newArray[$checkedId]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With