为每个月的数组增加价值

时间:2018-07-22 09:40:23

标签: php json laravel-5

我有一组循环的分支。我想添加报告部分,就像下面的json输出一样。我正在使用laravel作为我的json API。

分支结果来自数据库。

$month  = array("January","February","March","April","May","June",
          "July","August","September","October","November","December");

这是我当前的代码..卡在这里

$result         = $branch;
for ($i = 0; $i < count($branch); $i++) {

      for ($col = 0; $col < count($month); $col++) {
        $result[$i]['report'] = ??
      }

    }

return(array("res"=>true,"branch"=>$result));

这是我经过处理后的预期输出

{
"res": true,
"branch": [{
        "com_branch_id": 7,
        "report": {
            "January": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "Febuary": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "March": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "April": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "May": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "Jun": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "July": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "August": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "September": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "October": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "November": {
                "totalSales": "400",
                "Profit": "1000"
            },
            "December": {
                "totalSales": "400",
                "Profit": "1000"
            }
        }
    },

]

}

希望有人可以帮助解决这个问题。。谢谢。

1 个答案:

答案 0 :(得分:0)

您还没有完全指定$ branch结构,但是我相信下面的代码逻辑可能有助于阐明您的问题。

for ($i = 0; $i < count($branch); $i++) {

    for ($col = 0; $col < count($month); $col++) {
         $result[$i]['report'][$month[$col]] = $branch[$i][$month[$col]];
    }

}
return(array("res"=>true,"branch"=>$result));