如何在 while 循环中创建多维数组?
我在 php 中遇到了这个简单的问题:
$words = array();
while ($allrow = mysqli_fetch_array($all))
{
$words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"]."";
}
foreach ($words[] as $key => $word) {
我想要一个包含一些单词及其 id 的数组。在 foreach 循环中,我需要能够知道每个单词有哪个 id。
Im stuck with this simple problem in 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. In the foreach loop I need to be able to know which id each word has.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的数组构建语法已关闭,请尝试以下操作:
每次您说
$words = $anything
时,您都会覆盖最后一次迭代。这应该会产生一个解析错误:
不知道你的测试是如何忽略它的。也不需要空的
""
字符串。You array building syntax is off, try this:
Every time you say
$words = $anything
, you are overwriting the last iteration.This should have generated a parse error:
Not sure how that slipped by your testing. No need for the empty
""
strings either.在 foreach 循环中,将每个条目添加到数组中。
如果您确实希望 id 作为键(更有可能),则可以反转分配:
同样,您不应该使用
$words[]
进行迭代。这没有道理。使用foreach($words as $key => $value)
由于使用
[]
分配数组值和迭代数组是基本概念,因此您应该学习 PHP 数组 在尝试使用它们之前。Inside your foreach loop, add each entry to the array.
if you actually want the id as the key, which is more probable, you reverse the assignment:
As well, you should not iterate using
$words[]
. That does not make sense. Useforeach($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.然后在 foreach 循环中使用
foreach ($words as $key => $word) {
and then in the foreach loop use
foreach ($words as $key => $word) {