$posts = array(
"message" => 'this is a test message'
);
foreach ($posts as $post) {
echo $post['message'];
}
为什么上面的代码只输出消息中的第一个字母? “T”。
谢谢!
答案 0 :(得分:12)
foreach获取数组的每个元素并将其赋值给变量。为了得到结果,我假设您只是需要这样做:
foreach ($posts as $post) {
echo $post;
}
有关代码无法工作的具体细节:$post
将是数组元素的内容 - 在本例中为字符串。因为PHP不是强类型/支持类型杂耍,所以你实际上可以使用字符串,就像它是一个数组一样,并获取序列中的每个字符:
foreach ($posts as $post) {
echo $post[0]; //'t'
echo $post[1]; //'h'
}
因此$post['message']
显然不是有效的元素,并且没有从(string)'message'
到int
的明确转换,因此这将转变为$post[0]
。
答案 1 :(得分:6)
# $posts is an array with one index ('message')
$posts = array(
"message" => 'this is a test message'
);
# You iterate over the $posts array, so $post contains
# the string 'this is a test message'
foreach ($posts as $post) {
# You try to access an index in the string.
# Background info #1:
# You can access each character in a string using brackets, just
# like with arrays, so $post[0] === 't', $post[1] === 'e', etc.
# Background info #2:
# You need a numeric index when accessing the characters of a string.
# Background info #3:
# If PHP expects an integer, but finds a string, it tries to convert
# it. Unfortunately, string conversion in PHP is very strange.
# A string that does not start with a number is converted to 0, i.e.
# ((int) '23 monkeys') === 23, ((int) 'asd') === 0,
# ((int) 'strike force 1') === 0
# This means, you are accessing the character at position ((int) 'message'),
# which is the first character in the string
echo $post['message'];
}
你可能想要的是:
$posts = array(
array(
"message" => 'this is a test message'
)
);
foreach ($posts as $post) {
echo $post['message'];
}
或者这个:
$posts = array(
"message" => 'this is a test message'
);
foreach ($posts as $key => $post) {
# $key === 'message'
echo $post;
}
答案 2 :(得分:4)
我想补充iAn的答案:如果你想以某种方式访问值的键,请使用:
foreach ($posts as $key => $post) {
echo $key . '=' . $post;
}
结果:
message=this is a test message