2011-09-29 79 views
0

這裏是新的,但喜歡閱讀別人的問題和答案。我對PHP相當陌生,正在開發一個項目 - 在MySQL中查找基本表格等。 我最終想要的是一個數組數組,其形式如下所示(不是我的實際項目)。內容來自兩個不同的表格。對於每個調味品名稱(來自表1),我在表2中查找通過ID鏈接的調味品的類型。搜索和抓取的東西很好,但我無法循環和建立我最後的$ Condiments數組。從sql結果數組中迭代附加數組

循環的第一部分,我從$行中獲取調味品名稱並將其追加到數組中。但我需要這些調味品名稱中的每一個都是一個空數組,以便在下一步中放入某些東西。我環顧四周,但無法找到一個好的方法來迭代地將新的佔位符數組附加到數組中。有沒有優雅的解決方案?一些很酷的功能,我沒有利用?謝謝!

// SQL search for condiment words, blah blah, leading to... 
$rowsnumber = mysql_num_rows($result); 

for ($j = 0 ; $j < $rowsnumber ; ++$j) 
    { 
    $row = mysql_fetch_row($result); // $row is an array featuring a condiment name and other stuff. 
    $Condiments[] = $row[1]; // condiment name goes in array. 
    $CondimentType = searchTable2($row[0]); 
    // using the condiment name's ID, I look up its matching types via a function. 
    // $CondimentType is now an array of IDs and types from Table2 that I want to append to the condiment name I just added above. 
     $Condiments[$row[1]] = $CondimentType; 
    // I repeat the process for the next name 
    } 

// Final desired result... 
$Condiments= 
Array 
(
    [Pickles] => Array 
     (
      [34] => Dill 
      [23] => Butter 
     ) 
    [Mustard] => Array 
     (
      [22] => Hot 
     ) 
    [Relish] => Array 
     (
      [3] => Pickle 
     ) 
) 
+0

如果你可以發佈你的數據庫的模式,它會幫助我們很多。從我所瞭解的情況來看,你似乎需要加入這兩張表來加速這個過程 –

+0

@Don接近我的真實項目。基本上是兩個表格,一個是文字,另一個是將單詞連接在一起。一位朋友還建議使用SQL來合併表格信息。不知道如何在評論字段中更好地顯示。 'INSERT INTO表1(ID,字)參數值 ( '25', '醬菜'), ( '74', '芥末'), ( '85', '津津樂道'), ( '34' ,'Dill'), ('23','Butter'), ('22','Hot'), ('3','Pickle'); INSERT INTO表2(ID,鏈路ID)VALUES ( '25', '34'), ( '25', '23'), ( '74', '22'), ( '85', '3');' –

回答

0

所以就像我說的,你需要使用加入到執行所需的任務。

,你可以在這裏找到更多的解釋關於你的情況加入

http://dev.mysql.com/doc/refman/5.0/en/join.html

,這個查詢應該做

select t1.word,t3.word 
from table1 as t1 join table2 as t2 on t1.id =t2.id 
left join table1 as t3 on t3.id = t2.linkid 

我跑在我的機器上查詢的工作,這些都是結果

+---------+--------+ 
| word | word | 
+---------+--------+ 
| Pickles | Dill | 
| Pickles | Butter | 
| Mustard | Hot | 
| Relish | Pickle | 
+---------+--------+ 

所以不是循環每一行,只需執行一次連接並獲得結果。在PHP中,然後你可以做所需的數組格式。 希望這會幫助你

+0

非常感謝 - 將實驗... –