Update value in array()

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
    )

)

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


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]


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];

Need Your Help

Elevating from low to medium integrity

windows windows-vista uac integrity

This is similar to " how create medium integrity level process from low integrity level process? ", but I'm coming from a slightly different angle. (And that isn't answered anyway.) :)

Sending emails with ASP.NET

c# asp.net newsletter

I am building a web site, and the client wants a newsletter "system" on it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.