简体   繁体   中英

PHP Nested for-each loop

$QRYS1 = QUERY;
$QRYS2 = QUERY;
$QRYS3 = QUERY;
$QRYS4 = QUERY;

foreach($QRYS1 as $QRY1)
{
 foreach($QRYS2 as $QRY2)
 {
   if(bla)
   {
   foreach($QRYS3 as $QRY3)
   {
     foreach($QRYS4 as $QRY4)
     {

     }
   }
  }
 }
}

The above style of code makes data processing very slow. Is there anyway I can make the processing fast?

I am getting the data doing joining and counting with multiple tables and its all ARRAY().

fetching table using for-each loop will slow down your page. You can try joining of tables and fetch those fields which you want.

<?php

$TotalCountofDepartmentforSelectedComp_id = Userlog::where('userlogs.company_id', '=', $comp_id)
    ->where_Between('userlogs.created_at', $startDate, $endDate)
    ->group_by('userlogs.department_id')
    ->get(['userlogs.department_id', DB::raw('count(userlogs.user_id) as totaldepartmentcount')]);

$ProductListforSelectedComp_id = Product::join('userlogs', 'userlogs.product_id', '=', 'products.id')
    ->where('userlogs.company_id', '=', $comp_id)
    ->distinct()
    ->get(['products.id', 'products.name']);


$TotalCountCompanyProductWiseinforSelectedComp_id = Product::join('userlogs', 'userlogs.product_id', '=', 'products.id')
    ->where('userlogs.company_id', '=', $comp_id)
    ->where_Between('userlogs.created_at', $startDate, $endDate)
    ->group_by('products.id')
    ->get(['products.id', DB::raw('count(userlogs.user_id) as totalcompanyproductcountuserwise')]);

$DepartmentListsforSelectedComp_id = Department::where('company_id', '=', $comp_id)->get(
    ['departments.id', 'departments.name']
);


$TotalCountCompanyDepartmentProductWiseinforSelectedComp_id = DB::query(
    'SELECT T1.id, T2.department_id,
            COALESCE(T2.totaldepartmentproductcountuserwise, 0) AS totaldepartmentproductcountuserwise
       FROM (
         SELECT DISTINCT products.id FROM products
           INNER JOIN userlogs ON userlogs.product_id = products.id
           WHERE company_id = ?
         ) AS T1
       LEFT JOIN (
         SELECT department_id, product_id, COUNT(*) AS totaldepartmentproductcountuserwise
           FROM userlogs
           WHERE company_id = ?
             AND created_at BETWEEN ? AND ?
           GROUP BY department_id, product_id
         ) AS T2 ON T2.product_id = T1.id',
    array($comp_id, $comp_id, $startDate, $endDate)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM