Home > Backend Development > PHP Tutorial > 多维数组中相同元素相加有关问题

多维数组中相同元素相加有关问题

WBOY
Release: 2016-06-13 11:17:53
Original
1132 people have browsed it

多维数组中相同元素相加问题

本帖最后由 myths621 于 2013-03-19 12:04:11 编辑 首次发帖,请假高手
我从redis中取出五维数组需要处理相加,如下
<br />$a = array(<br />	<br />		0 => array(<br /><br />			0=> array(<br />			<br />				"date" => "201201",<br />				"area"=> array(<br />					12 => array(<br />						click => "3",<br />						traffic => "30"<br />					)	<br />				)<br />			),	<br /><br />			1=> array(<br />			<br />				"date" => "201202",<br />				"area"=> array(<br />					12 => array(<br />						click => "8",<br />						traffic => "40"<br />					),<br />					8=> array(<br />						click => "5",<br />						traffic => "50"<br />					)<br />				)<br />			)	<br />			<br />		),<br /><br />		1 => array(<br />		<br />			0=> array(<br />			<br />				"date" => "201201",<br />				"area"=> array(<br />					12 => array(<br />						click => "9",<br />						traffic => "20"<br />					),<br />					8=> array(<br />						click => "6",<br />						traffic => "60"<br />					)<br />				)<br />				),<br />			<br />			1=> array(<br />			<br />				"date" => "201202",<br />				"area" => NULL<br />			)<br />		),<br />	<br />	<br />	);<br /><br />
Copy after login


希望数据处理后,相同date前提下,area里相同的key所对应的click和traffic值相加,即0和1这两个大数组,date为201001的,area中12所对应的click和traffic处理后应该是12和50,8对应的是6和60,其他类推,求遍历或其他能处理成功的方法,感激不尽~!
多维数组


------解决方案--------------------
最后结果是怎么样的? 贴一下。
------解决方案--------------------
$t = array();<br />foreach ($a as $k=>$v)<br />{<br />	foreach ($v as $k1=>$v1)<br />	{<br />		$t[0][$k1]['date'] = $v1['date'];<br />		foreach ($v1['area'] as $k2=>$v2)<br />		{<br />			$t[0][$k1]['area'][$k2]['click'] += $v2['click'];<br />			$t[0][$k1]['area'][$k2]['traffic'] += $v2['traffic'];<br />		}<br />	}<br />}<br />echo "<pre class="brush:php;toolbar:false">";<br />print_r($t);<br />echo "<pre class="brush:php;toolbar:false">";
Copy after login


结果如下:
<br>Array<br>(<br>    [0] => Array<br>        (<br>            [0] => Array<br>                (<br>                    [date] => 201201<br>                    [area] => Array<br>                        (<br>                            [12] => Array<br>                                (<br>                                    [click] => 12<div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template