Elio Chamy
Elio Chamy

Reputation: 269

Laravel for loop return data in in array

I have 1 brand and 2 branches in my database, I'm getting the sales data for each branch.

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;

My problem is :

Upvotes: 0

Views: 1054

Answers (3)

Ankit Vaishnav
Ankit Vaishnav

Reputation: 46

Use array_push function to append new variables:

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

Upvotes: 0

Onix
Onix

Reputation: 2179

Change your netstellar to this (and keep it inside of for loop) :

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

and return this :

return $netsalesdata[];

Upvotes: 1

Naincy
Naincy

Reputation: 2943

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

Upvotes: 0

Related Questions