php - 循环通过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)
我哪里错了?
解决方案
您需要用单引号将数组键括起来,因为它们是字符串类型。
所以,
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']
用单引号将数组键括起来始终是一个好习惯。
巧合的是,如果定义了相同的常量,则该常量的值可以被视为数组键。
如果未定义常量,则会显示警告。
推荐阅读
- django - 发送电子邮件时,Django 会发出信号吗?
- python - Python正则表达式-如何捕获未捕获的其余文本
- sql - 如何从 Sql Server 中的字符串中获取值,
- android - FirebaseRecylcerVAdapter 从最高到最低排序
- python - DataFrame 到 Json,使用第一个 Col 作为键,第二个作为值
- maven - 持久类似乎没有得到增强。您可能需要重新运行增强器并检查输出中的错误。”
- r - R-如何有条件地删除 group_by 的第一行
- java - Lucene:建立索引
- entity-framework - 如何在 Azure Function 的应用程序设置中定义 providername 属性
- python - 如何生成总和=1的随机值列表