Problems with multiple arrays forming another array
The following array is formed in the program (the key in the program is dynamic, and here it is written dead)
Array
(
[Category] = Total
[January2014_number_stores] = 0
[February2014_number_stores] = 0
[March2014_number_stores] = 0
)
And there's an 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
)
Now you want to assign the sum of the same key value in the array in the second set to the first array, how do I write it? How do I write if the key value is dynamic and regular?
------Solution--------------------
$a = 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);
Array
(
[Category] = Total
[January2014_number_stores] = 331
[February2014_number_stores] = 331
[March2014_number_stores] = 331
)