2017-03-06 24 views
0

我在数据库中有1个品牌和2个分支,我得到每个分支的销售数据。Laravel for循环返回数组中的数据

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个分支
+0

如果DD($分支机构);你有两个分支吗? – Onix

回答

1

更改您的netste LLAR这个(并保持它在for循环):

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

,并返回此:

return $netsalesdata[]; 
+0

工作谢谢 –

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]); 
} 
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; 
}