PHP 多维数组帮助
我正在从 MySQL 数据库填充一个数组,问题是我在下拉框中出现 9 个空白字段,我试图用它们填充它。我做错了什么?
php代码:
while($row = mysql_fetch_assoc($results))
{
$options[] = array(
Name => $row['Name'],
Value => $row['Value'],
ID => $row['CID']
);
}
下拉框:
for ($i = 0; $i < 9; $i++)
{
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'
.$options[$i]["Name"].
'</option>'."\n";
}
I am populating an array from a MySQL Database, the problem is I get 9 blank fields in my dropdown box that I am trying to populate it with. What did I do wrong?
php code:
while($row = mysql_fetch_assoc($results))
{
$options[] = array(
Name => $row['Name'],
Value => $row['Value'],
ID => $row['CID']
);
}
dropdown box:
for ($i = 0; $i < 9; $i++)
{
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'
.$options[$i]["Name"].
'</option>'."\n";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的数组中的引号是向后的
此外,在双引号中使用关联数组需要您这样做:
如果您不这样做,它(应该)会导致解析错误。
您可能会注意到这也有效,
但这不是一个好的做法,因为如果通过 Define() 命名索引存在常量,则所有语句都将使用常量的定义而不是您想要的字符串。
Your quotes are backwards in your array
Also, using an associative array in double quotes requires you to do this:
If you don't do it this way, it (should) result in a parse error.
You might notice that this also works
But this is not good practice because if there is a constant through a define() named index, all of your statements will use your constant's definition instead of the string you intended.
假设您的查询实际执行,问题在于如何将数组值初始化为数组键。在PHP中,关联数组的键必须是字符串,并且PHP中的字符串用单引号或双引号引起来。
访问关联数组还需要使用字符串作为键:
当在双引号字符串内使用数组时,要获取它们的值,您应该用大括号将数组括起来:
请注意,您可以使用带有常规变量的大括号技术:
如果您只想保存对于所有行,您可以只存储整个
$row
数组:而不是将每个单独的值从一个数组复制到另一个数组。这更简洁、更易读、更不容易出错,并且如果
$row
的内容发生变化,它也会泛化。当然,如果$row
的内容发生变化,这就存在需要更改依赖于$options
的内容的陷阱。Assuming your query actually executes, the problem is with how you're initializing your array values to your array keys. In PHP, the keys of an associative array must be strings, and strings in PHP are quoted with single or double quotes.
Accessing associative arrays also requires using strings for keys:
When using arrays inside double quoted strings, to get their value you should surround the arrays with braces:
Note you can use the technique for braces with regular variables:
If all you want to do is save all your rows, you can just store the whole
$row
array:rather than copying each individual value from array to array. This is more concise, more readable, less error prone, and will generalize if the contents of
$row
changes. Of course, if the content of$row
changes, this has the pitfall of requiring changes to things that depend on$options
.您必须引用数组键
Name、Value、ID
:在
"$row['key']"
两边加上引号是不必要且多余的。PHP 数组文档
You must quote the array keys
Name, Value, ID
:Placing quotes around the
"$row['key']"
is unnecessary and redundant.The PHP array documentation