繁体   English   中英

如何减少PHP脚本中的执行时间?

[英]How do I reduce the execution time in my script in PHP?

这是我的脚本,需要很长时间,如何改善执行时间?

查看所有的鳕鱼:在这里

$count_nr_attributes = count($nume);
$csv[0] = $csv_array_attributes[0];
for ($i=0; $i < $csv_array_attributes; $i++) { 

        if ($i > 0){
            $final = "";
            for ($j=1; $j < $count_nr_attributes; $j++) { 
                echo "select val_attr from attributes where id_produs = '$csv_array_attributes[$i]' and nume_attr = '$nume[$j]'";echo "<br>";
                $select = mysql_query("select val_attr from attributes where id_produs = '$csv_array_attributes[$i]' and nume_attr = '$nume[$j]'");
                $count = mysql_num_rows($select);
                if ($count == 1){
                    $row = mysql_fetch_array($select);
                    $final .= $row['val_attr']."%%";
                }else{
                    $final .= "no%%";
                }
            }
            echo "<hr>";

        }
        $csv[$i] = $csv_array_attributes[$i]."%%".$final;
    }
//create CSV
$file = fopen("attributes.csv","w+");
    foreach ($csv as $line){
        fputcsv($file,explode('%%',$line),"^","`");
    }

变量$count_nr_attributes包含的值超过2500,而$ csv_array_attributes包含的值则超过2500。 实际上我有两个for循环,执行时间太长。 我该如何改善呢? 谢谢

查询结果总是返回一个值;

每次执行SQL查询时,无论返回多少结果,都需要花费一些时间。

减少脚本花费的时间,您能做的最好的事情就是将查询放在循环之外 ,一次获取所有结果,然后在循环之后处理它。

首先:不要使用mysql_ *。 无论如何,请尝试使用尽可能少的查询来重做此操作。 我现在没有时间分析所有意图,但可以尝试以下方法:

$count_nr_attributes = count($nume);
$csv[0] = $csv_array_attributes[0];

$query = "
SELECT id_produs, nume_attr, val_attr FROM attributes WHERE 
id_produs IN (".implode(",", $csv_array_attributes).") AND nume_attr BETWEEN 0 AND {$count_nr_attributes} 
ORDER BY id_produs";

$res = mysql_query($query);
$lastProduct = -1;
while($row = mysql_fetch_array($res)) {
  //do whatever you want
  //just check if id_produs is different than the previous one to emulate
  //$csv[$i] = $csv_array_attributes[$i]."%%".$final;
}

使用键为id_produs的关联数组,并在该内部循环之后使用其值,再次使用关联数组来获取与第一个关联数组有关的所有记录,希望这会减少一点时间。 谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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