数组和foreach

5 php arrays

$posts = array(
"message" => 'this is a test message'
);

foreach ($posts as $post) {
     echo $post['message'];
}
Run Code Online (Sandbox Code Playgroud)

为什么上面的代码只输出消息中的第一个字母?"T".

谢谢!

Ian*_*Ian 12

foreach获取数组的每个元素并将其分配给变量.为了得到结果,我假设你只是需要做:

foreach ($posts as $post) {
   echo $post;
}
Run Code Online (Sandbox Code Playgroud)

关于你的代码无法工作的具体细节:$post将是数组元素的内容 - 在本例中是一个字符串.因为PHP不是强类型/支持类型杂耍,所以你实际上可以使用字符串,就好像它是一个数组,并获取序列中的每个字符:

foreach ($posts as $post) {
    echo $post[0]; //'t'
    echo $post[1]; //'h'
}
Run Code Online (Sandbox Code Playgroud)

显然,$post['message']因此不是一个有效的元素,并没有明确的转换,从(string)'message'int,所以这evals来$post[0].


sou*_*rge 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'];
}
Run Code Online (Sandbox Code Playgroud)

您可能想要的是这样的:

$posts = array(
    array(
        "message" => 'this is a test message'
    )
);
foreach ($posts as $post) {
    echo $post['message'];
}
Run Code Online (Sandbox Code Playgroud)

或这个:

$posts = array(
    "message" => 'this is a test message'
);
foreach ($posts as $key => $post) {
    # $key === 'message'
    echo $post;
}
Run Code Online (Sandbox Code Playgroud)