2012-07-16 88 views
0

我試圖獲取分配給特定子類別 (id = 9)的配置文件名稱。當我運行下面的代碼時,我得到了我想要的配置文件,但對於某些 原因,foreach循環中的ORDER BY子句不按字母順序排列它們的名稱 。相反,它們的排列方式與「子類別」表中 「配置文件」字段中的順序相同(配置文件的ID以逗號分隔)。 例如,如果在子類別[「剖面」]我已經」,5,1,2' 輪廓名稱將按照以下順序顯示 :在MySQL中的順序子句不在foreach循環內工作

  1. 資料與ID = 5
  2. 資料ID爲= 1
  3. 資料與ID = 2

我使用的爆炸()函數來獲取「子類別」 表內的各輪廓的ID,然後使用該ID從檢索其信息'profile'表使用 foreach循環內的查詢。

我在這裏錯過了什麼嗎?謝謝你的幫助。

這裏是我的代碼:

<?php 
$subcategories=mysql_query("select * from subcategories where id='9'"); 

while ($subcategories = mysql_fetch_array($subcategories)) 

{ 
$profiles = $subcategories['profiles']; 
$profiles = explode(',', $profiles); 

     foreach ($profiles as $p) 
     { 
     $all_places = mysql_query("select * from profile where id='$p' and active='1' order by name asc"); 

      while ($profile = mysql_fetch_array($all_places)) 
      { 

       echo $profile['name'];     

      } 

     } 

} 
?> 
+0

如果沒有'ORDER BY'子句(如果被排除),它工作正常嗎? – Lion 2012-07-16 09:02:12

+0

是的,它工作正常。 – 2012-07-16 09:26:52

回答

1

那麼爲什麼你的結果不按名稱排序的原因是因爲你檢索與一個新的SQL查詢中的每個配置文件在你的foreach循環爲$配置文件。在您的情況下,如果有效,您最終將得到3個SQL查詢,每個查詢返回1個配置文件。因此,當聲明「order by」子句時,它在每個查詢中按名稱排序,每個查詢只包含1個結果。

是否使用IN語句適合您?例如。

<?php 
$subcategories=mysql_query("select * from subcategories where id='9'"); 

while ($subcategories = mysql_fetch_array($subcategories)) 

{ 

//i assume $subcategories['profiles'] are integers separated by comma as mentioned 
$profiles = $subcategories['profiles']; 

       $all_places = mysql_query("select * from profile where id IN ($profiles) and active='1' order by name asc"); 

        while ($profile = mysql_fetch_array($all_places)) 
        { 

         echo $profile['name'];     

        } 

} 
?> 
+0

我剛想出了另一種方法來做到這一點。我沒有從子類別表中選擇配置文件ID,而是使用MySQL語句中的LIKE選擇了具有該子類別ID的所有配置文件。 $子類別= '9'; $ subcategories1 = mysql_query(「select * from profile where LIKE'%$ subcategories%'AND active ='1'order by name asc」);我也刪除了內部的foreach和while循環,因爲它們不再需要。現在看起來工作正常,謝謝。 – 2012-07-16 09:34:18

+0

它似乎現在正常工作,除了一個小問題:如果我有子類別ID 9和19上述查詢將返回兩個。任何想法如何克服這一點? – 2012-07-16 10:00:03

+0

問題解決了,我嘗試了你的建議和它的工作。我只需要從$ profiles字符串中刪除第一個逗號,因爲它導致了一個問題。謝謝你的幫助! – 2012-07-16 11:29:22