PHP嵌套for-each循环

时间:2016-01-22 13:35:08

标签: php foreach

$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)
     {

     }
   }
  }
 }
}

上述代码风格使数据处理速度非常慢。无论如何我可以快速处理?

我正在使用多个表及其所有ARRAY()进行连接和计数的数据。

2 个答案:

答案 0 :(得分:4)

使用for-each循环获取表格会降低页面速度。您可以尝试连接表并获取所需的字段。

答案 1 :(得分:0)

<?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));