PHP for循环会影响页面加载速度吗?

时间:2010-01-26 08:32:43

标签: php performance

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);

for($x=0;$x<count($categs);$x++){
    for($y=0;$y<count($categories);$y++){
        if($categs[$x] == $categories[$y]){
            $str .= $y.",";
        }
    }
}

echo str; // 0,3,1,

此代码会影响页面渲染时间吗?我可以使用任何其他快速方法吗?

提前致谢。

5 个答案:

答案 0 :(得分:2)

$str = implode(',', array_keys(array_intersect($categories, $categs)));

答案 1 :(得分:0)

您可以使用array_intersect()查找常用项目,然后使用implode()构建以逗号分隔的列表:

Str = implode(',', array_intersect($categories, $categs)) . ',';

除非您处理大量项目(数千),否则不会影响页面速度。一个问题是这个交叉点是O(n 2 )。将值放入键可以大大加快它的速度,因为这会将查找时间从O(n)更改为接近O(1),从而使整个操作成为O(n)。

答案 2 :(得分:0)

我不认为str_replace比所有数组函数更快,但另一种可能的解决方案是:

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query

foreach($categories as $i=> $c) {
     $sql = str_replace($c, $i, $sql);   
}

答案 3 :(得分:0)

是的,因为你循环循环。

最好的事情是在数组中查看:

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);
$str = array();

foreach($categs as $id => $categs_check)
{
    if(in_array($categs_check, $categories))
    {
        //its better to put it into a array and explode it on a later point if you need it with comma.
        $str[] = $id;
    }
}

我不完全确定你要做什么,但它应该像上面那样

答案 4 :(得分:0)

$arrCategories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$arrCategs = explode(",",$sql);
$arrAns = array();

for($i = 0, $intCnt = count($arrCategs); $i <= $intCnt; $i++) {
    if(in_array($arrCategs[$i],$arrCategories)) {
        $arrAns[$arrCategs[$i]] = array_search($arrCategs[$i], $arrCategories);
    }
}

print "<pre>";
print_r($arrAns);
print "</pre>";