Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update value in array()

Tags:

arrays

php

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
    )

)


2 Answers

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

like image 195
ioseb Avatar answered May 11 '26 04:05

ioseb


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]

like image 20
Tesserex Avatar answered May 11 '26 04:05

Tesserex