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

时间:2017-03-06 10:47:14

标签: php laravel

我的数据库中有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循环中,我只获得第一个原始数据(仅限1个分支)
  • 如果我把它放在循环之外,我得到最后一行(仅第二个分支),而我的数据库有2个分支

3 个答案:

答案 0 :(得分:1)

将您的netstellar更改为此(并将其保留在for循环中):

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

并返回:

return $netsalesdata[];

答案 1 :(得分:0)

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')
               ->select(DB::raw('sum(AMOUNT) as TOT')->get();

        $ytdnetsales= DB::table('st_sales')
               ->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

   // get size of the array
   $records = count($netsalesdata);
   // To get last record
   print_r($netsalesdata[$records -1]);
}

答案 2 :(得分:0)

使用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;
}