本文以1,2,3,4,5将数据分组,求和
$users = array( array('id'=>1,'age'=>'1'), array('id'=>2,'age'=>'2'), array('id'=>3,'age'=>'3'), array('id'=>4,'age'=>'4'), array('id'=>5,'age'=>'5'), array('id'=>1,'age'=>'1'), array('id'=>2,'age'=>'2'), array('id'=>3,'age'=>'3'), array('id'=>4,'age'=>'4'), array('id'=>5,'age'=>'5'), array('id'=>1,'age'=>'1'), array('id'=>2,'age'=>'2'), array('id'=>3,'age'=>'3'), array('id'=>4,'age'=>'4'), array('id'=>5,'age'=>'5'), ); $newArr = [];//存放求和的值 $arr = [];//里面放新数组 foreach ($users as $key => $value) { //在新数组就age相加 if (in_array($value['id'],$arr)) { $newArr[$value['id']] += $value['age']; } else { //不在新数组就将age存入$newArr $arr[] = $value['id']; $newArr[$value['id']] = $value['age']; } } echo "<pre>"; print_r($newArr);
结果如下: /*Array ( [1] => 3 [2] => 6 [3] => 9 [4] => 12 [5] => 15 )*/