合并php数组重复值 [英] Combine php array duplicate values

查看:63
本文介绍了合并php数组重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

,然后我想合并重复的值,添加 qnty 索引值,并按如下所示打印该数组:

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

推荐答案

尝试下面的代码。我假设您的数组名称为 $ products

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;

这篇关于合并php数组重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆