在 Heredoc 内的 key 中使用带有空格的数组元素

发布于 2025-01-16 05:08:28 字数 810 浏览 2 评论 0原文

我正在从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自找没趣 2025-01-23 05:08:28

使用大括号和引号:

<?php
$a = array(
    'first_element' => 'test1',
    'second element' => 'test2'
);

$html = <<<EOF
first element is: {$a['first_element']}
second element is: {$a['second element']}
EOF;

Heredoc 语法,示例#8

Use curly brackets and quotes:

<?php
$a = array(
    'first_element' => 'test1',
    'second element' => 'test2'
);

$html = <<<EOF
first element is: {$a['first_element']}
second element is: {$a['second element']}
EOF;

heredoc syntax, Example #8

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文