多个数组形成另一个数组的有关问题
程序员文章站
2022-06-05 16:14:25
...
多个数组形成另一个数组的问题
程序中形成了以下的数组(程序的中的key是动态的,这里写死了)
又有数组
现在要把第二组中的数组中key值相同的相加求和后赋值给第一个数组,该怎么写? 如果key值是动态有规律的该怎么写?
------解决方案--------------------
(
[Category] => TOTAL
[January2014_Number_stores] => 331
[February2014_Number_stores] => 331
[March2014_Number_stores] => 331
)
程序中形成了以下的数组(程序的中的key是动态的,这里写死了)
Array
(
[Category] => TOTAL
[January2014_Number_stores] => 0
[February2014_Number_stores] => 0
[March2014_Number_stores] => 0
)
又有数组
Array
(
[January2014_Number_stores] => 155
[February2014_Number_stores] => 155
[March2014_Number_stores] => 155
)
Array
(
[January2014_Number_stores] => 126
[February2014_Number_stores] => 126
[March2014_Number_stores] => 126
)
Array
(
[January2014_Number_stores] => 37
[February2014_Number_stores] => 37
[March2014_Number_stores] => 37
)
Array
(
[January2014_Number_stores] => 9
[February2014_Number_stores] => 9
[March2014_Number_stores] => 9
)
Array
(
[January2014_Number_stores] => 4
[February2014_Number_stores] => 4
[March2014_Number_stores] => 4
)
现在要把第二组中的数组中key值相同的相加求和后赋值给第一个数组,该怎么写? 如果key值是动态有规律的该怎么写?
------解决方案--------------------
$a = array(Array
'Category' => 'TOTAL',
'January2014_Number_stores' => 0,
'February2014_Number_stores' => 0,
'March2014_Number_stores' => 0,
);
$b = array(
array(
'January2014_Number_stores' => 155,
'February2014_Number_stores' => 155,
'March2014_Number_stores' => 155,
),
array(
'January2014_Number_stores' => 126,
'February2014_Number_stores' => 126,
'March2014_Number_stores' => 126,
),
array(
'January2014_Number_stores' => 37,
'February2014_Number_stores' => 37,
'March2014_Number_stores' => 37,
),
array(
'January2014_Number_stores' => 9,
'February2014_Number_stores' => 9,
'March2014_Number_stores' => 9,
),
array(
'January2014_Number_stores' => 4,
'February2014_Number_stores' => 4,
'March2014_Number_stores' => 4,
),
);
foreach($b as $r) {
foreach($r as $k=>$v) {
if(! isset($a[$k])) $a[$k] = 0;
$a[$k] += $v;
}
}
print_r($a);
(
[Category] => TOTAL
[January2014_Number_stores] => 331
[February2014_Number_stores] => 331
[March2014_Number_stores] => 331
)
相关文章
相关视频
上一篇: php 如何判断是否收藏过
下一篇: PHP 高级编程(4/5)_PHP教程