【问题标题】:add value to each month array向每个月数组添加值
【发布时间】:2025-12-09 22:55:02
【问题描述】:

我有一组循环的分支。我想像下面的 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"
            }
        }
    },

]

}

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

【问题讨论】:

标签: php json laravel-5


【解决方案1】:

您尚未完全指定 $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));

【讨论】:

  • 这是我的分支,$branch = DbConnectBranch::select('com_branch_name','com_branch_id')->where("com_branch_comId",$getApiKey->comId)->get();
  • 错误:间接修改app\Http\Connection\DbConnectBranch的重载元素无效