Php 数组中循环返回数据的Laravel

Php 数组中循环返回数据的Laravel,php,laravel,Php,Laravel,我的数据库中有1个品牌和2个分支机构,我正在获取每个分支机构的销售数据 public function getCurrentSales($brandid){ $branches = DB::table('gc_branch')->where('BRAND_ID', $brandid) ->select('BRANCHID', 'BRANCHNAME')

我的数据库中有1个品牌和2个分支机构,我正在获取每个分支机构的销售数据

public function getCurrentSales($brandid){
$branches = DB::table('gc_branch')->where('BRAND_ID', $brandid)
                                  ->select('BRANCHID', 'BRANCHNAME')
                                  ->get(); 

for ($i=0; $i<count($branches);$i++){
$mtdnetsales= DB::table('st_sales')
//query
->select(DB::raw('sum(AMOUNT) as TOT')->get();

$ytdnetsales= DB::table('st_sales')
//query
->select(DB::raw('sum(AMOUNT) as TOT')->get();


$netsalesdata=[['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]];

}//end for

return $netsalesdata;
我的问题是:

如果将返回值$netsalesdata放入for循环,则只会得到第一个raw-only-1分支 如果我把它放在循环之外,我只得到最后一行第二个分支,而我的数据库有两个分支
将NetTellar更改为此,并将其保留在for循环中:

$netsalesdata[$i]=[['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]];
并将此返回:

return $netsalesdata[];

使用array_push函数附加新变量:

public function getCurrentSales($brandid){
    $netsalesdata= [];
    $branches = DB::table('gc_branch')->where('BRAND_ID', $brandid)
                                      ->select('BRANCHID', 'BRANCHNAME')
                                      ->get(); 

    for ($i=0; $i<count($branches);$i++){
        $mtdnetsales= DB::table('st_sales')
        //query
        ->select(DB::raw('sum(AMOUNT) as TOT')->get();

        $ytdnetsales= DB::table('st_sales')
        //query
        ->select(DB::raw('sum(AMOUNT) as TOT')->get();


        array_push($netsalesdata, ['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]);

     }//end for

     return $netsalesdata;
}

如果您添加了$分支;两个分支都有吗?
public function getCurrentSales($brandid){
    $netsalesdata= [];
    $branches = DB::table('gc_branch')->where('BRAND_ID', $brandid)
                                      ->select('BRANCHID', 'BRANCHNAME')
                                      ->get(); 

    for ($i=0; $i<count($branches);$i++){
        $mtdnetsales= DB::table('st_sales')
        //query
        ->select(DB::raw('sum(AMOUNT) as TOT')->get();

        $ytdnetsales= DB::table('st_sales')
        //query
        ->select(DB::raw('sum(AMOUNT) as TOT')->get();


        array_push($netsalesdata, ['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]);

     }//end for

     return $netsalesdata;
}