首页 > 解决方案 > 循环通过PHP数组,错误日志说未定义的常量

问题描述

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

Array
(
    [section] => Array
        (
            [345dfg] => Array
                (
                    [test] => Array
                        (
                            [name] => John
                        )
                )
            [567fghj] => Array
                (
                    [test] => Array
                        (
                            [name] => Tom
                        )
                )
        )
    [othersection] => Array
        (
            [result] => 2
        )
)

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

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

    echo $section[test][name];

}

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

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

我哪里错了?

标签: phparrays

解决方案


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

所以,

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

应该

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

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

可能性$data['section']

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

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

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

用单引号将数组键括起来始终是一个好习惯。

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

如果未定义常量,则会显示警告。


推荐阅读