Home  >  Article  >  php教程  >  php二维数组合并与元素值相加实例

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

WBOY
WBOYOriginal
2016-06-08 17:25:521713browse

php教程二维数组合并与元素值相加实例
*/
$arr_click = array(
    array('date' => '2010-10-01', 'click' =>'1'),
    array('date' => '2010-10-02', 'click' =>'2'),
    array('date' => '2010-10-02', 'click' =>'3'),
    array('date' => '2010-10-03', 'click' =>'4'),
);

$temp = array();

foreach ($arr_click as $k => $v)
{
    $key = $v['date'];
    $temp[$key] = isset($temp[$key]) ? $v['click'] + $temp[$key] : $v['click'];
}

foreach ($temp as $k => $v)
{
    $result[] = array('date' => $k, 'click' => $v);
}

var_dump($result);

//方法二

$arr_click = array(
array( 'date' => '2010-10-01', 'click' =>'1' ),
array( 'date' => '2010-10-02', 'click' =>'2' ),
array( 'date' => '2010-10-02', 'click' =>'3' ),
array( 'date' => '2010-10-03', 'click' =>'4' ),
);
foreach($arr_click as $v)
  if($r[$v['date']]) $r[$v['date']]['click'] += $v['click'];
  else $r[$v['date']] = $v;
$arr_click = array_values($r);

print_r($arr_click);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn