PHP:foreach周期缓慢

时间:2018-01-07 15:36:31

标签: php performance foreach cycle

以下脚本非常慢 - 表“users”现在有大约13.000行。任何想法如何修改它来加快它?谢谢!

<?php

    $first = 0;
    $second = 0;
    $third = 0;
    $fourth = 0;

    foreach ($_SESSION['subordinates'] as $key => $subordinateId) {
        $q1 = mysql_num_rows(mysql_query ("SELECT id FROM users WHERE id=$subordinateId and dogs = 0 and cats = 0"));
        $first = $first  + $q1;

        $q2 = mysql_num_rows(mysql_query ("SELECT id FROM users WHERE id=$subordinateId and (cats=1 or cats=1)"));
        $second = $second + $q2;

        $q3 = mysql_num_rows(mysql_query ("SELECT id FROM users WHERE id=$subordinateId and dogs = 0 and cats = 0 and myDate > SUBDATE(NOW(), INTERVAL 1 MONTH)"));
        $third = $thirth + $q3;   

        $q4 = mysql_num_rows(mysql_query ("SELECT id FROM users WHERE id=$subordinateId and (dogs = 1 or cats = 1) and myDate > SUBDATE(NOW(), INTERVAL 1 MONTH)"));
        $fourth = $fourth + $q4;
    } 

    ?>

1 个答案:

答案 0 :(得分:0)

可能不是PHP循环缓慢,而是MySQL查询。你可以尝试在表中添加一些索引,就像这样。

CREATE INDEX user_index_on_dogs ON users (dogs);
CREATE INDEX user_index_on_cats ON users (cats);
CREATE INDEX user_index_on_dogs_and_cats ON users (dogs, cats);
CREATE INDEX user_index_on_my_date ON users (myDate);

另外,您可能需要查看Official MySQL reference about CREATE INDEXhow mysql uses these indexes