I have an array, when I json_decode()
it, I got below array:
Array
(
[avg] => 1.1
[day] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
[channels] => Array
(
[ali] => Array
(
[amount] => 5
[rate] => 6
)
)
)
Array
(
[avg] => 3.3
[day] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[channels] => Array
(
[ali] => Array
(
[amount] => 5
[rate] => 8
)
)
)
How can I merge these arrays into one, meanwhile, I want all the values to be calculated as average, such as (1.1+3.3)/2 = 2.2
. We have to loop the channels
sub array, because it's dynamic, ie. not only ali
but also several channels as well may appear.
So the supposed result should be: (All the structure of the sub arrays are same)
Array
(
[avg] => 2.2
[day] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[channels] => Array
(
[ali] => Array
(
[amount] => 5
[rate] => 7
)
)
)
What I tried is very complicated. First, I pop the first array in the arrays, and loop the left array to sum all of the values of them. Once done, I loop the array again to calculate the average value, but it costs about 30 lines of code. I don't think it's a very good way to do this. Is there a more suitable way to do this?