此代码的目标是将所有商店的所有品牌放入一个数组中,并将其输出到屏幕上。如果一个品牌存在于多个商店中,则只会添加一次。
但我觉得我的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:13:02
您的表是如何设计的?如果您有一个商店表、一个品牌表和一个具有商店和品牌之间关系的链接表,那么您可以只在一个查询中从品牌表中拉入品牌列表,而不必执行任何其他逻辑。
设计你的表格,让它们很容易回答你需要问的问题。
https://stackoverflow.com/questions/2137272
复制相似问题