关于多维数组的PHP问题
我的数组看起来像这样:
Array ( [Bob] => Red [Joe] => Blue )
但它可以是任意数量的人,像这样:
Array ( [Bob] => Red [Joe] => Blue [Sam] => Orange [Carla] => Yellow)
基本上我希望 PHP 获取这个数组并回显它,以便它看起来像:
Bob - Red
Joe - Blue
Sam - Orange
Carla - Yellow
我知道我需要循环遍历该数组,这就是我尝试过:
for ($row = 0; $row < count($array); $row++) {
echo $array[0] . " - " . $array[1];
}
我收到以下错误:未定义的偏移量:0,未定义的偏移量:1
我意识到这不起作用,因为当数组的值是字符串时我尝试使用索引。有什么方法可以将这样的位置索引与仅包含字符串的多维数组一起使用吗?
谢谢
My array looks like this:
Array ( [Bob] => Red [Joe] => Blue )
But it could be any number of people, like this:
Array ( [Bob] => Red [Joe] => Blue [Sam] => Orange [Carla] => Yellow)
Basically I want PHP to take this array and echo it so that it comes out looking like:
Bob - Red
Joe - Blue
Sam - Orange
Carla - Yellow
I know I need to loop through the array, this is what I tried:
for ($row = 0; $row < count($array); $row++) {
echo $array[0] . " - " . $array[1];
}
I get the following error: Undefined offset: 0, Undefined offset: 1
I realize that this doesn't work because I'm trying to use index's when the values of the array are strings. Is there any way I can use positional index's like this with a multidimensional array that only contains strings?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要的是一个
foreach
循环。(如果您想要换行符,请在末尾附加
"\n"
)您的数组实际上不是多维。例如,请
注意数组内的数组。
您的数组通常称为关联数组。
What you want is a
foreach
loop.(if you want a newline, append
"\n"
to the end)Your array is actually not multidimensional. An example of that would be
Note the array within the array.
Your array is generally called an associative array.
无需重新检查我的 php 知识:
Without re-checking my php knowledge:
你需要一个
foreach
会打印:
顺便说一下,它是一个关联数组,而不是多维数组,它更像是:
You need a
foreach
Will print:
By the way, it is a
associative
array, not amultidimensional
one, which is more something like: