阵列和foreach [英] Array and foreach
问题描述
$posts = array(
"message" => 'this is a test message'
);
foreach ($posts as $post) {
echo $post['message'];
}
为什么上面的code只能输出在消息的第一个字母? T。
Why does the above code only output the first letter in message? "t".
谢谢!
推荐答案
的foreach采取数组中的每个元素,并将其分配给变量。为了让我相信你期待你的结果只需要做:
foreach takes each element of the array and assigns it to the variable. To get the results I assume you are expecting you just need to do:
foreach ($posts as $post) {
echo $post;
}
的细节,为什么你的code没有工作: $岗位
将数组元素的内容 - 在这种情况下的字符串。因为PHP不是强类型/类型支持杂耍,你可以在一个字符串的工作其实就好像它是一个数组,并获得序列中的每个字符:
The specifics as to why your code didn't work: $post
would be the contents of the array element - in this case a string. Because PHP isn't strongly typed / supports type juggling, you can in fact work with a string as if it were an array, and get to each character in the sequence:
foreach ($posts as $post) {
echo $post[0]; //'t'
echo $post[1]; //'h'
}
显然 $信息['消息']
因此它不是一个有效的元素,并有从没有明确的转换(字符串)信息
到 INT
,所以这个evals到 $讯息[0]
。
Obviously $post['message']
therefore is not a valid element, and there is no explicit conversion from (string)'message'
to int
, so this evals to $post[0]
.
这篇关于阵列和foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!