0

I have an array:

Array
(
    [0] => Array
        (
            [qty] => 2
            [id] => 1
            [name] => Name 1
            [sku] => Model 1
            [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
            [price] => 209.00
        )

    [1] => Array
        (
            [qty] => 1
            [id] => 1
            [name] => Name 1
            [sku] => Model 1
            [options] => Color: <em>Black (+10$)</em>. Memory: <em>16GB</em>. 
            [price] => 110.00
        )

    [2] => Array
        (
            [qty] => 1
            [id] => 3
            [name] => Name 2
            [sku] => Model 2
            [options] => 
            [price] => 100.00
        )
)

First step is to find the same id. And if the same id exist convert array. Is it possible to get output array (if id the same remove one and add qty to the another)?

 Array
    (
        [0] => Array
            (
                [qty] => 3 // 2+1
                [id] => 1
                [name] => Name 1
                [sku] => Model 1
                [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
                [price] => 209.00
            )
    
        [1] => Array
            (
                [qty] => 1
                [id] => 3
                [name] => Name 2
                [sku] => Model 2
                [options] => 
                [price] => 100.00
            )
    )
2
  • 1
    then what about price and options??? Commented Jun 27, 2013 at 6:31
  • If you don't care about the other attributes, it shouldbe pretty easy with a foreach loop. What have you tried and what was the problem? Commented Jun 27, 2013 at 6:36

1 Answer 1

1
$result = array();
foreach ($input as $subarray) {
  $id = $subarray['id'];
  if (isset($result[$id])) { // Same ID
    $result[$id]['qty'] += $subarray['qty']; // Add quantities
  } else {
    $result[$id] = $subarray; // New ID, put in results
  }
}
$result = array_values($result); // Convert from associative array to indexed
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.