이 코드의 목표는 모든 상점의 모든 브랜드를 하나의 배열로 가져와이를 화면에 출력하는 것입니다. 브랜드가 여러 매장에있는 경우 한 번만 추가됩니다.성능 향상을 위해이 PHP 코드를 단순화 할 수 있습니까?
하지만 루프가 너무 많아 트래픽이 많을 때 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;
}
데이터베이스 테이블과 실행중인 쿼리에 대해 자세히 알려 줄 수 있습니까? 하나의 데이터베이스 쿼리와 올바른 조인을 사용하는 하나의 루프로 줄일 수있는 좋은 기회가 있습니다. –