php二维数组合并与元素值相加实例

  1. */
  2. $arr_click = array(
  3. array('date' => '2010-10-01', 'click' =>'1'),
  4. array('date' => '2010-10-02', 'click' =>'2'),
  5. array('date' => '2010-10-02', 'click' =>'3'),
  6. array('date' => '2010-10-03', 'click' =>'4'),
  7. );
  8. $temp = array();
  9. foreach ($arr_click as $k => $v)
  10. {
  11. $key = $v['date'];
  12. $temp[$key] = isset($temp[$key]) ? $v['click'] + $temp[$key] : $v['click'];
  13. }
  14. foreach ($temp as $k => $v)
  15. {
  16. $result[] = array('date' => $k, 'click' => $v);
  17. }
  18. var_dump($result);
  19. //方法二
  20. $arr_click = array(
  21. array( 'date' => '2010-10-01', 'click' =>'1' ),
  22. array( 'date' => '2010-10-02', 'click' =>'2' ),
  23. array( 'date' => '2010-10-02', 'click' =>'3' ),
  24. array( 'date' => '2010-10-03', 'click' =>'4' ),
  25. );
  26. foreach($arr_click as $v)
  27. if($r[$v['date']]) $r[$v['date']]['click'] += $v['click'];
  28. else $r[$v['date']] = $v;
  29. $arr_click = array_values($r);
  30. print_r($arr_click);