3

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
    )

)

1
  • 1
    Are the ID's that are similar always next to eachother or not? Commented Nov 30, 2011 at 17:07

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

1

you could do this with some foreach loops, or you could make your life much easier by changing your array structure to be something more like this:

  Array (
    [39584] => 4
    [39574] => 1
  )

Then to add quantities, it would be as simple as:

$main_array[$id] = $main_array[$id] + $new_array[$id];

Comments

0

Each array has a position already in the parent array so if you want the first set then you call it: $var[0][quantity] mind you, why do you have multiple arrays with the same id?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.