通过PHP数组循环,错误日志显示未定义的常量

fig*_*r20 -2 php arrays

我有一个看起来像这样的PHP数组$ data ...

Array
(
    [section] => Array
        (
            [345dfg] => Array
                (
                    [test] => Array
                        (
                            [name] => John
                        )
                )
            [567fghj] => Array
                (
                    [test] => Array
                        (
                            [name] => Tom
                        )
                )
        )
    [othersection] => Array
        (
            [result] => 2
        )
)
Run Code Online (Sandbox Code Playgroud)

我试图遍历每个项目,section所以这样做...

foreach ($data[section] as $section) {

    echo $section[test][name];

}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是在我的错误日志中,我得到...

PHP Warning:  Use of undefined constant section- assumed 'section' (this will throw an Error in a future version of PHP)
Run Code Online (Sandbox Code Playgroud)

我要去哪里错了?

Pup*_*pil 5

您需要使用单引号将数组键括起来,因为它们是字符串类型。

所以,

foreach ($data[section] as $section) {
Run Code Online (Sandbox Code Playgroud)

应该

foreach ($data['section'] as $section) {
Run Code Online (Sandbox Code Playgroud)

否则,没有$符号且没有单引号的section将被视为constant

具有$data['section']以下可能性:

1)$section作为变量:$data[$section]

2)section作为常量:$data[section]

3)section作为数组键(字符串):$data['section']

将数组键括在单引号中始终是一个好习惯。

碰巧的是,如果定义了相同的常量,则可以将该常量的值视为数组键。

如果未定义常量,它将显示警告。