我的数据库中有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个分支)答案 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;
}