php 二维数组 合并相同项 指定元素相加
$arr = array( array( 'user_id' => 100, 'goods_id' => 10, 'number' => 1, ), array( 'user_id' => 100, 'goods_id' => 10, 'number' => 2, ), array( 'user_id' => 100, 'goods_id' => 10, 'number' => 2, ), array( 'user_id' => 100, 'goods_id' => 10, 'number' => 2, ), ); $item=array(); foreach($arr as $k=>$v){ if(!isset($item[$v['user_id']])){ $item[$v['user_id']]=$v; }else{ $item[$v['user_id']]['number']+=$v['number']; } } print_r($item);
执行结果:
Array ( [100] => Array ( [user_id] => 100 [goods_id] => 10 [number] => 7 ) )
说明:使user_id值相同的数组对应的number值相加。