php foreach echo 将“数组”打印为值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13485156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php foreach echo prints "Array" as value
提问by Edge D-Vort
Perhaps I'm simply having trouble understanding how php handles arrays.
也许我只是无法理解 php 如何处理数组。
I'm trying to print out an array using a foreach loop. All I can seem to get out of it is the word "Array".
我正在尝试使用 foreach 循环打印出一个数组。我似乎只能摆脱“阵列”这个词。
<?php
$someArray[]=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?>
<br />
<?php
}
?>
This prints out this:
这打印出来:
Array
I'm having trouble understanding why this would be the case. If I define an array up front like above, it'll print "Array". It almost seems like I have to manually define everything... which means I must be doing something wrong.
我无法理解为什么会这样。如果我像上面一样预先定义一个数组,它将打印“数组”。似乎我必须手动定义所有内容……这意味着我一定做错了什么。
This works:
这有效:
<?php
$someArray[0] = '1';
$someArray[1] = '2';
$someArray[2] = '3';
$someArray[3] = '4';
$someArray[4] = '5';
$someArray[5] = '6';
$someArray[6] = '7';
for($i=0; $i<7; $i++){
echo $someArray[$i]."<br />";
}
?>
Why won't the foreach work?
为什么 foreach 不起作用?
here's a link to see it in action >> http://phpclass.hylianux.com/test.php
这里有一个链接可以查看它的实际效果 >> http://phpclass.hylianux.com/test.php
回答by Lior
You haven't declared the array properly.
You have to remove the square brackets: [].
您没有正确声明数组。
您必须删除方括号:[]。
<?php
$someArray=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?> <br />
<?php
}
?>
回答by Twisty
Try:
尝试:
<?php
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value . "<br />\n";
}
?>
Or:
或者:
<?php
$someArray = array(
0 => '1',
'a' => '2',
2 => '3'
);
foreach($someArray as $key => $val){
echo "Key: $key, Value: $val<br/>\n";
}
?>
回答by Frank
actually, you're adding an array into another array.
实际上,您正在将一个数组添加到另一个数组中。
$someArray[]=array('1','2','3','4','5','6','7');
the right way would be
正确的方法是
$someArray=array('1','2','3','4','5','6','7');

