在 Heredoc 内的 key 中使用带有空格的数组元素
我正在从 MySQL 数据库中提取数据并以关联数组的形式获取结果,但数据库中的字段有空间,因此我必须访问键中带有空格的数组元素,现在如果我只访问该元素并将密钥用引号引起来,但我想在定界文档中使用它,并且访问数组元素时遇到问题。
一个显示问题的示例,
<?php
$a = array(
'first_element' => 'test1',
'second element' => 'test2'
);
$html = <<<EOF
first element is: $a[first_element]
second element is: $a[second element]
EOF;
?>
因为键没有空格,所以第一个元素可以很好地打印,第二个元素则不能,
Parse error: syntax error, unexpected string content "", expecting "]" in /Applications/XAMPP/xamppfiles/htdocs/installments/test.php on line 9
如果我尝试将键用引号引起来,则会出现此错误
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in /Applications/XAMPP/xamppfiles/htdocs/installments/test.php on line 9
I'm pulling data from a MySQL database and getting the result as an associative array but the fields in the database have space so I have to access the array element with spaces in the key, now that is fine if I just access the element and wrap the key in quotes, but I want to use it in a heredoc and I have a problem accessing the array elements.
An example to show the problem
<?php
$a = array(
'first_element' => 'test1',
'second element' => 'test2'
);
$html = <<<EOF
first element is: $a[first_element]
second element is: $a[second element]
EOF;
?>
the first element can be printed fine since the key doesn't have spaces, the second element can't and resulting in this error
Parse error: syntax error, unexpected string content "", expecting "]" in /Applications/XAMPP/xamppfiles/htdocs/installments/test.php on line 9
if i try to wrap the key in quotes i get another error
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in /Applications/XAMPP/xamppfiles/htdocs/installments/test.php on line 9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用大括号和引号:
Heredoc 语法,示例#8
Use curly brackets and quotes:
heredoc syntax, Example #8