-3

I have a php array that just like this:

Array
(
    [0] => Array
        (
            [product] => 2
            [price] => 30
            [qnty] => 1
        )
    [1] => Array
        (
            [product] => 2
            [price] => 30
            [qnty] => 1
        )
    [2] => Array
        (
            [product] => 1
            [price] => 250
            [qnty] => 1
        )
)

and I want to combine the duplicate values, add "qnty" index value and print that array like this:

Array
(
    [0] => Array
        (
            [product] => 2
            [price] => 30
            [qnty] =>2
        )
    [1] => Array
        (
            [product] => 1
            [price] => 250
            [qnty] => 1
        )
)

How can i combine this array. Please help me

1
  • Iterate over the array, check for duplicate items of the current, if so, remove the duplicates and increase qnty Commented Dec 4, 2013 at 11:52

1 Answer 1

1

try the code below. I am assuming the your array name is $products

$merged = array();
  foreach($products as $product) {
  $key = $product['product'];

  if(!array_key_exists($key, $merged)) {
      $merged[$key] = $product;
  }
  else {
      $merged[$key]['qnty'] += $product['qnty'];
  }
}
 echo '<pre>';
 print_r($merged);
 exit;
Sign up to request clarification or add additional context in comments.

1 Comment

hi, Thanks for the code. but i getting this error: Warning: array_key_exists(): The first argument should be either a string or an integer

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.