2011-03-08 43 views
0

我有一個名爲「精選」(int,默認爲0)的列的產品表。當我在第一個位置添加特色產品時,它會在此列中添加值「1」,在第二個位置上添加「2」等等。 。 我的問題是,當我沒有產品的第一或第二的位置,但只有在第三或第二個,它會「促進」第一個位置上的第三個產品。 有沒有辦法使用默認選擇查詢中的產品填充未提升的職位(例如:第一位或第二位),並在第三位顯示特色產品的「特色」值爲3?通過專題排序 - php mysql

回答

1

基本上,你需要跟蹤的功能是什麼您填寫插槽,哪些是你需要填寫的。您可能還擔心,如果您的列表不是足夠長,你的所有功能插槽......所以,你可以這樣做:

$qh = mysql_query('SELECT featured, ... FROM products ORDER BY featured DESC'); 

//get the featured rows first; 
while($row = mysql_fetch_assoc($qh)) { 
    if($row['featured'] > 0) { 
     $featured[$row['featured']] = $row; 
    } else { 
     break; 
    } 
} 
//values were inserted in reverse, so reorder them. 
ksort($featured); 

$idx = 1; 
//make sure there was a next row from above while loop 
if($row) { 
    do { 
     //print any featured rows that should appear at position $idx 
     while(isset($featured[$idx])) { 
      printRow($featured[$idx]); 
      $idx++; 
     } 
     //$idx doesn't have a featured row, so print a non-featured one 
     printRow($row); 
     $idx++; 
    } while($row = mysql_fetch_assoc($qh)); 
} 

//print any remaining featured rows 
foreach($featured as $key => $value) { 
    if($featured >= $idx) { 
     printRow($value); 
    } 
} 
+0

您必須選擇所有產品的問題,您keysort將只是做與mysql orderby相同,WHERE精選> 0。不需要在php imo中對此進行排序。另外我不明白你如何填補普通產品的空白? – Erik 2011-03-09 08:18:05

+0

@Erik,如果我有'WHERE featured> 0',那麼我就不會有任何非特色產品。當然,我可以用'ORDER BY'創造更多的創意,這樣就不需要重新排序鍵(類似於'ORDER BY featured = 0,featured')。我填補了do-while循環中的空白。同時打印內部特色的人,直到找到一個空白,然後我打印一個非功能的時間。如果不清楚,那麼'$ featured'數組中的每個索引都不會有值。 – jswolf19 2011-03-09 13:23:28

+0

當然,如果多個項目具有相同的特徵值,則會更加複雜,但在問題中沒有提及。 – jswolf19 2011-03-09 13:24:12

0

其實真的很容易。 只需進行選擇查詢,並且您還要求提供精選。 在php中,您可以查看第一個有特色的號碼。 如果它大於1,則選擇正常產品。 一個小例子:

$resultsOther = array(); 
$result = executeQuery('SELECT featured, name, ~~ FROM products WHERE featured > 0 ORDER BY featured'); 
if($results[0]['featured'] > 1) { 
    $resultsOther = // get other products with a limit on the query 
} 
foreach ($resultsOther as $r) { 
    print_r($r); 
} 
foreach ($results as $r) { 
    print_r($r); 
} 

你可以做到這一點的另一種方式是:

// This will select max 5 items and if there are not enough featured items it also selects non featured. 
$results = execute('SELECT featured, ~~ FROM products ORDER BY featured DESC LIMIT 5'); 
while ($result = array_pop($results)) { 
    print_r($result); // verander deze door de functie om de producten te tonen. 
}