结合php数组重复值

时间:2013-12-04 11:51:40

标签: php arrays

我有一个像这样的php数组:

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
        )
)

我想组合重复的值,添加“ qnty ”索引值并打印出这样的数组:

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

我如何组合这个数组。请帮帮我

1 个答案:

答案 0 :(得分:1)

尝试下面的代码。我假设您的数组名称为$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;