此代码的目标是将所有商店的所有品牌放入一个数组中,并将其输出到屏幕上。如果一个品牌存在于多个商店中,则只会添加一次。
但我觉得我的for循环太多了,而且它可能会在繁忙的流量中阻塞CPU。有没有更好的解决方案?
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;
}发布于 2010-01-26 11:51:33
在您的评论中,您提到"Guide table有X个门店,每个门店有Y个品牌“。大概有一个“商店”表、一个“品牌”表和一个“链接”表,它们以一家商店对多个品牌的关系将store_id与brand_id配对,对吧?
如果是这样的话,一个SQL查询就可以完成您的任务:
SELECT b.`id`, b.`name`
FROM `stores` s
LEFT JOIN `linkage` l
ON l.`store`=s.`id`
LEFT JOIN `brands` b
ON b.`id`=l.`brand`
GROUP BY b.`id`;最后的GROUP BY子句将只显示每个品牌一次。如果您删除它,您可以添加商店ID并输出商店到品牌关联的完整列表。
发布于 2010-01-26 11:17:52
不需要遍历两组数组(一组用于构建品牌数组,另一组用于生成HTML)。特别是因为您的helper函数会遍历--使用array_key_exists函数并使用ID作为键。此外,您可以使用implode函数来连接带有',‘的链接,这样您就不必手动操作(在您现有的代码中,您必须修剪掉末尾的逗号)。您可以在不使用两组for循环的情况下完成此操作:
function getBrands($stores, $bl)
{
$brands = array();
//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 (!array_key_exists($row['id'])
{
$url = get_bloginfo('url') . '/searchbrandID=' .
$brand['id'] . '&brand=' . urlSanitize($brand['name']);
$brands[$row['id']] .= '<a href="' . $url . '" id="' .
$brand['id'] . '" target="_self">' .
$brand['name'] . '</a>';
}
}
}
return implode(', ', $html);
}这将使您更快地获得相同的效果。这将会更快,因为您过去需要循环获取品牌,然后循环并构建HTML。不需要将其作为两个单独的循环来执行,因此可以一次完成所有操作,并且只需存储HTML即可。此外,由于它切换到使用array_key_exists,而不是您编写的通过再次循环检查是否存在品牌的帮助器,您将看到更多的速度改进。hashmap很好用,因为hashmap中的每个元素都有一个键,并且有一些本机函数可以查看键是否存在。
您可以通过编写一个更好的SQL语句和一个独特的过滤器来进一步优化它,这样您就不必在foreach中执行一段时间。
发布于 2010-01-26 11:13:02
您的表是如何设计的?如果您有一个商店表、一个品牌表和一个具有商店和品牌之间关系的链接表,那么您可以只在一个查询中从品牌表中拉入品牌列表,而不必执行任何其他逻辑。
设计你的表格,让它们很容易回答你需要问的问题。
https://stackoverflow.com/questions/2137272
复制相似问题