数组何并

下雨的声音丶 2016-08-10 03:34:09
Array
(
[0] => Array
(
[goods_id] => 590
[goods_num] => 1
[goods_pay_price] => 2000.00
)

[1] => Array
(
[goods_id] => 626
[goods_num] => 2
[goods_pay_price] => 2000.00
)

[2] => Array
(
[goods_id] => 628
[goods_num] => 1
[goods_pay_price] => 1000.00
)

[3] => Array
(
[goods_id] => 628
[goods_num] => 2
[goods_pay_price] => 2000.00
)

[4] => Array
(
[goods_id] => 626
[goods_num] => 2
[goods_pay_price] => 2000.00
)

)
怎么快速把这个数组合并起来 ,相同goods_id 的goods_num和goods_pay_price分别加起来
...全文
80 点赞 收藏 1
写回复
1 条回复
xuzuning 2016年08月10日
$a = array (
  0 => 
  array (
    'goods_id' => '590',
    'goods_num' => '1',
    'goods_pay_price' => '2000.00',
  ),
  1 => 
  array (
    'goods_id' => '626',
    'goods_num' => '2',
    'goods_pay_price' => '2000.00',
  ),
  2 => 
  array (
    'goods_id' => '628',
    'goods_num' => '1',
    'goods_pay_price' => '1000.00',
  ),
  3 => 
  array (
    'goods_id' => '628',
    'goods_num' => '2',
    'goods_pay_price' => '2000.00',
  ),
  4 => 
  array (
    'goods_id' => '626',
    'goods_num' => '2',
    'goods_pay_price' => '2000.00',
  ),
);
$r = [];
array_map(function($v) use (&$r) {
  $r[$v['goods_id']]['goods_id'] = $v['goods_id'];
  @$r[$v['goods_id']]['goods_num'] += $v['goods_num'];
  @$r[$v['goods_id']]['goods_pay_price'] += $v['goods_pay_price'];
  }, $a);
print_r($r);
Array
(
    [590] => Array
        (
            [goods_id] => 590
            [goods_num] => 1
            [goods_pay_price] => 2000
        )

    [626] => Array
        (
            [goods_id] => 626
            [goods_num] => 4
            [goods_pay_price] => 4000
        )

    [628] => Array
        (
            [goods_id] => 628
            [goods_num] => 3
            [goods_pay_price] => 3000
        )

)

回复 点赞
发动态
发帖子
基础编程
创建于2007-09-28

9734

社区成员

14.0w+

社区内容

从PHP安装配置,PHP入门,PHP基础到PHP应用
社区公告
暂无公告