PHP for loop will affect the page load speed?
$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,
Will this code will affect page render time? Ca开发者_C百科n I do it using any other fast methods?
Thanks in advance.
$str = implode(',', array_keys(array_intersect($categories, $categs)));
You can use array_intersect()
to find the common items and then use implode()
to construct a comma-separated list:
Str = implode(',', array_intersect($categories, $categs)) . ',';
Unless you're dealing with a large number of items (thousands) it won't affect page speed. The one issue is that this intersection is O(n2). Putting the values into keys could speed it up considerably as that changes lookup time from O(n) to near O(1) making the whole operation O(n).
yes it will since you are looping in a loop.
Best thing is to check with in array:
$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;
}
}
I'm not completely sure what you are trying to do but it should be something like the above
I don't think that str_replace
is a faster method than all the array functions but another possible solution is:
$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);
}
$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>";
精彩评论