[英]How to do a multidimensional array within a while loop?
我在 php 中遇到了這個簡單的問題:
$words = array();
while ($allrow = mysqli_fetch_array($all))
{
$words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"]."";
}
foreach ($words[] as $key => $word) {
我想要一個包含一些單詞及其 id 的數組。 在 foreach 循環中,我需要能夠知道每個單詞有哪個 id。
您的數組構建語法已關閉,請嘗試以下操作:
// array key is the id, swap if needed, but I assume the ids are unique
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
每次您說$words = $anything
時,您都在覆蓋最后一次迭代。
這應該會產生一個解析錯誤:
."" => "".
不知道你的測試是如何滑倒的。 也不需要空的""
字符串。
在您的 foreach 循環中,將每個條目添加到數組中。
$words[utf8_encode($allrow["eng"])] = $allrow["id"];
如果您實際上希望 id 作為鍵,這更有可能,您可以反轉分配:
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
同樣,您不應該使用$words[]
進行迭代。 那沒有意義。 利用foreach($words as $key => $value)
由於使用[]
分配數組值和迭代 arrays 是基本概念,因此在嘗試使用它們之前,您應該研究PHP arrays 。
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
然后在 foreach 循環中使用foreach ($words as $key => $word) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.