[英]How to do a multidimensional array within a while loop?
Im stuck with this simple problem in php:我在 php 中遇到了这个简单的问题:
$words = array();
while ($allrow = mysqli_fetch_array($all))
{
$words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"]."";
}
foreach ($words[] as $key => $word) {
I wanna have an array with some words and its id.我想要一个包含一些单词及其 id 的数组。 In the foreach loop I need to be able to know which id each word has.
在 foreach 循环中,我需要能够知道每个单词有哪个 id。
You array building syntax is off, try this:您的数组构建语法已关闭,请尝试以下操作:
// array key is the id, swap if needed, but I assume the ids are unique
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
Every time you say $words = $anything
, you are overwriting the last iteration.每次您说
$words = $anything
时,您都在覆盖最后一次迭代。
This should have generated a parse error:这应该会产生一个解析错误:
."" => "".
Not sure how that slipped by your testing.不知道你的测试是如何滑倒的。 No need for the empty
""
strings either.也不需要空的
""
字符串。
Inside your foreach loop, add each entry to the array.在您的 foreach 循环中,将每个条目添加到数组中。
$words[utf8_encode($allrow["eng"])] = $allrow["id"];
if you actually want the id as the key, which is more probable, you reverse the assignment:如果您实际上希望 id 作为键,这更有可能,您可以反转分配:
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
As well, you should not iterate using $words[]
.同样,您不应该使用
$words[]
进行迭代。 That does not make sense.那没有意义。 Use
利用
foreach($words as $key => $value)
As assigning array values with []
and iterating arrays are basic concepts, you should study up on PHP arrays before trying to use them.由于使用
[]
分配数组值和迭代 arrays 是基本概念,因此在尝试使用它们之前,您应该研究PHP arrays 。
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
and then in the foreach loop use foreach ($words as $key => $word) {
然后在 foreach 循环中使用
foreach ($words as $key => $word) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.