doufei4923 2014-04-07 13:05
浏览 64
已采纳

首先根据值合并两个数组,然后根据key-php合并第二个数组

I have two arrays

First array named "$periods" and second array named "$groupExport" like below.

First Array - $periods

Array
(
    [0] => 201308
    [1] => 201309
    [2] => 201310
)

Second Array - $groupExport

Array
(
    [0] => Array
        (
            [GroupCode] => 111
            [GroupDesc] => Crop Production
            [201308] => 1.5500
            [201309] => 240.4200
            [201310] => 41.2110
        )

    [1] => Array
        (
            [GroupCode] => 112
            [GroupDesc] => Animal Production
            [201309] => 3.1800
        )

    [2] => Array
        (
            [GroupCode] => 115
            [GroupDesc] => Agriculture, Forestry Support
            [201308] => 234.0400
            [201310] => 343.0200
        )
)

I have tried atleast 5-6 different code ideas, it does not yields the below output. I want the output like below, so that I can display the resultset in table format according to the header GroupCode, GroupDesc, 201308, 201309 & 201310. Could anyone help me to resolve this?

Output

Array
(
    [0] => Array
        (
            [GroupCode] => 111
            [GroupDesc] => Crop Production
            [201308] => 1.5500
            [201309] => 240.4200
            [201310] => 41.2110
        )

    [1] => Array
        (
            [GroupCode] => 112
            [GroupDesc] => Animal Production
            [201308] => 0
            [201309] => 3.1800
            [201310] => 0
        )

    [2] => Array
        (
            [GroupCode] => 115
            [GroupDesc] => Agriculture, Forestry Support
            [201308] => 234.0400
            [201309] => 0
            [201310] => 343.0200
        )
)
  • 写回答

2条回答 默认 最新

  • dongmaqiu6084 2014-04-07 13:10
    关注

    Loop through the $groupExport array and on each iteration, loop through the sub-array and check if the each one of the period index exists. If they don't, initialize them with 0.

    foreach ($groupExport as & $export) {
        foreach ($periods as $period) {
            if (!isset($export[$period])) {
                $export[$period] = 0;
            }
        }
    }
    

    Note the & before $export. It means we're passing the array by reference — it's modifying $groupExport on each iteration.

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline