首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >可以简化这段PHP代码以提高性能吗?

可以简化这段PHP代码以提高性能吗?
EN

Stack Overflow用户
提问于 2010-01-26 11:01:58
回答 4查看 171关注 0票数 0

此代码的目标是将所有商店的所有品牌放入一个数组中,并将其输出到屏幕上。如果一个品牌存在于多个商店中,则只会添加一次。

但我觉得我的for循环太多了,而且它可能会在繁忙的流量中阻塞CPU。有没有更好的解决方案?

代码语言:javascript
运行
复制
  function getBrands($stores, $bl)
  {
    $html = "";

    //Loop through all the stores and get the brands
    foreach ($stores as $store)
    {
      //Get all associated brands for store
      $result = $bl->getBrandsByStore($store['id']);

      //Add all brands to array $brands[]
      while ($row = mysql_fetch_array($result))
      {
        //If this is the first run, we do not need to check if it already exists in array
        if(sizeof($brands) == 0)
        {
          $brands[] = array("id" => $row['id'], "name" => $row['name']);
        }
        else
        {
          // Check tosee if brand has already been added.
          if(!isValueInArray($brands, $row['id']))
            $brands[] = array("id" => $row['id'], "name" => $row['name']);
        }
      }
    }

    //Create the HTML output
    foreach($brands as $brand)
    {
      $url = get_bloginfo('url').'/search?brandID='.$brand['id'].'&brand='.urlSanitize($brand['name']);
      $html.= '<a href="'.$url.'" id="'.$brand['id'].'" target="_self">'.$brand['name'].'</a>, ';
    }

    return $html;
  }

  //Check to see if an ID already exists in the array
  function isValueInArray($values, $val2)
  {
    foreach($values as $val1)
    {
      if($val1['id'] == $val2)
        return true;
    }
    return false;
  }
EN

Stack Overflow用户

发布于 2010-01-26 11:13:02

您的表是如何设计的?如果您有一个商店表、一个品牌表和一个具有商店和品牌之间关系的链接表,那么您可以只在一个查询中从品牌表中拉入品牌列表,而不必执行任何其他逻辑。

设计你的表格,让它们很容易回答你需要问的问题。

票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2137272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档