dongxiangxie8181 2015-10-05 02:06
浏览 80

如何将多个格式的多维数组合并为一个数组,并使用PHP进行加权?

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
    • ¥15 关于#hadoop#的问题
    • ¥15 (标签-Python|关键词-socket)
    • ¥15 keil里为什么main.c定义的函数在it.c调用不了
    • ¥50 切换TabTip键盘的输入法
    • ¥15 可否在不同线程中调用封装数据库操作的类
    • ¥15 微带串馈天线阵列每个阵元宽度计算
    • ¥15 keil的map文件中Image component sizes各项意思