$arr = array(
array('id' => 123, 'name' => '张三', 'amount'=>'1'),
array('id' => 123, 'name' => '李四', 'amount' => '1'),
array('id' => 124, 'name' => '王五', 'amount' => '1'),
array('id' => 125, 'name' => '赵六', 'amount' => '1'),
array('id' => 126, 'name' => '赵六', 'amount' => '2'),
array('id' => 126, 'name' => '赵六', 'amount' => '2')
);
如果数组内的name相等,最终保留一个,但是amount的值相加。
请问这样如何处理?
天蓬老师2017-04-10 15:56:55
对数组进行一次遍历就可以了。
$arr = array(
array('id' => 123, 'name' => '张三', 'amount'=>'1'),
array('id' => 123, 'name' => '李四', 'amount' => '1'),
array('id' => 124, 'name' => '王五', 'amount' => '1'),
array('id' => 125, 'name' => '赵六', 'amount' => '1'),
array('id' => 126, 'name' => '赵六', 'amount' => '2'),
array('id' => 126, 'name' => '赵六', 'amount' => '2')
);
$new = array();
foreach($arr as $row){
if(isset($new[$row['name']])){
$new[$row['name']]['amount'] += $row['amount'];
}else{
$new[$row['name']] = $row;
}
}
print_r($new);