2011-06-30 132 views
0

林堅持這個簡單的問題,在PHP中:如何在while循環中做一個多維數組?

$words = array(); 
while ($allrow = mysqli_fetch_array($all)) 
{  
    $words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"]."";     
} 

foreach ($words[] as $key => $word) { 

我想有一些詞和其ID的數組。在foreach循環中,我需要能夠知道每個單詞有哪些id。

回答

2

您陣列建築語法是關閉的,試試這個:

// array key is the id, swap if needed, but I assume the ids are unique 
$words[$allrow["id"]] = utf8_encode($allrow["eng"]); 

你說的每$words = $anything時,要覆蓋上一次迭代。

這應該已經產生了解析錯誤:

."" => "". 

不知道如何通過你的測試下跌。不需要空的""字符串。

1

在您的foreach循環中,將每個條目添加到數組中。

$words[utf8_encode($allrow["eng"])] = $allrow["id"]; 

,如果你真的想要的ID爲關鍵,這更可能的是你扭轉分配:

$words[$allrow["id"]] = utf8_encode($allrow["eng"]); 

同樣,你不應該使用迭代$words[]。那沒有意義。使用
foreach($words as $key => $value)

[]分配數組值並遍歷數組的基本概念,你應該嘗試使用它們之前PHP arrays晚自習。

+0

我甚至沒有看最後一點,這個代碼是一個爛攤子。推薦閱讀基本PHP的+1。 –

0
$words[$allrow["id"]] = utf8_encode($allrow["eng"]); 

,然後在foreach循環使用foreach ($words as $key => $word) {