为什么此for循环PHP超级慢?

时间:2018-08-31 20:54:43

标签: php for-loop

为什么此for循环PHP超级慢?

我已经尽力将for循环最小化了,但是错误调试器在这里找不到问题?使用网站上的以下代码,页面响应在首次加载时为30秒,在第二,第三次时为8秒。

$modules_concat = "(CONCAT(',', `site_id`, ',') REGEXP ',(1|2),' AND m_type='my_table_name)";
$b2_s_v_a = '';

  for ($i = 1, $j = 168; $i <= 168, $j >= 0; $i++, $j--) {

    if ($i < 25) {
      $time_lang_for_start = $i+662;
      $time_lang_for_day = $lang['user_login_2'];
      $b2_time_hour = ($j-144)." HOUR AND HOUR(date_added) = ".($i-1);
      $b2_time_day = 'monday';
    } elseif ($i < 49) {
      $time_lang_for_start = $i+638;
      $time_lang_for_day = $lang['user_login_3'];
      $b2_time_hour = ($j-120)." HOUR AND HOUR(date_added) = ".($i-25);
      $b2_time_day = 'tuesday';
    } elseif ($i < 73) {
      $time_lang_for_start = $i+614;
      $time_lang_for_day = $lang['user_login_4'];
      $b2_time_hour = ($j-96)." HOUR AND HOUR(date_added) = ".($i-49);
      $b2_time_day = 'wednesday';
    } elseif ($i < 97) {
      $time_lang_for_start = $i+590;
      $time_lang_for_day = $lang['user_login_5'];
      $b2_time_hour = ($j-72)." HOUR AND HOUR(date_added) = ".($i-73);
      $b2_time_day = 'thursday';
    } elseif ($i < 121) {
      $time_lang_for_start = $i+566;
      $time_lang_for_day = $lang['user_login_6'];
      $b2_time_hour = ($j-48)." HOUR AND HOUR(date_added) = ".($i-97);
      $b2_time_day = 'friday';
    } elseif ($i < 145) {
      $time_lang_for_start = $i+542;
      $time_lang_for_day = $lang['user_login_7'];
      $b2_time_hour = ($j-24)." HOUR AND HOUR(date_added) = ".($i-121);
      $b2_time_day = 'saturday';
    } elseif ($i < 169) {
      $time_lang_for_start = $i+518;
      $time_lang_for_day = $lang['user_login_8'];
      $b2_time_hour = $j." HOUR AND HOUR(date_added) = ".($i-145);
      $b2_time_day = 'sunday';
    }

    $b2_n_o = 'test';

    $time_lang_for_get = $lang["user_login_$time_lang_for_start"];
    $time_ready_ch = 'time_ready_for_'.$i;
    $$time_ready_ch = $time_lang_for_day.', '.$time_lang_for_get;

    $b2_ch_v = 'b2_g_v_'.$i;
    $$b2_ch_v = $db->QueryGetNumRows("SELECT * FROM m_z_analytics WHERE $modules_concat AND date_added BETWEEN NOW() - INTERVAL 1 WEEK AND NOW() - INTERVAL $b2_time_hour AND DAYNAME(date_added) = '$b2_time_day'");

    $b2_s_v_a .= ${"b2_g_v_$i"};
    if ($i) {
      $b2_s_v_a .= ',';
    }

  }

示例文字。

1 个答案:

答案 0 :(得分:2)

最可能的原因是您的数据库查询被调用168次。您是否需要获取每列中的所有列(SELECT *)?如果不是,请指定所需的内容。您还可以尝试在更少的调用中获取所有数据,然后解析之后的需求。