Целью этого кода является получение всех брендов для всех магазинов в один массив и вывод его на экран. Если бренд существует в нескольких магазинах, он будет добавлен только один раз.Можно ли упростить этот PHP-код для повышения производительности?
Но я чувствую, что у меня слишком много для циклов, и это может затормозить процессор при интенсивном движении. Есть ли лучшее решение?
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;
}
Не могли бы вы рассказать нам больше о ваших таблицах базы данных и запросах, которые вы используете? Есть хороший шанс, что вы можете сократить его до одного запроса к базе данных и одного цикла, используя соответствующее соединение. –