如何将多维数组放入双引号字符串中?

10

我知道我可以在双引号中使用数组值,就像这样:

<?php echo "my name is: $arr[name]"; ?>

但是当我使用多维数组时,我无法看到我的结果:

<?php echo "he is $twoDimArr[family][1]"; ?>

这里的输出是:he is Array[1]

为什么会这样呢?

我知道可以像这样使用我的代码:

<?php echo "he is ".$twoDimArr[family][1]; ?>

但我不想要这个。


2
family 是一个常量吗? - Alon Eitan
2
数组在字符串中的默认表示仅限于一层。因此,如果您将项本身作为数组,则不会进一步解析它们。 - Mohit Bhardwaj
3
阅读文档:http://php.net/manual/zh/language.types.string.php#language.types.string.parsing - axiac
可能是PHP中关联数组的双引号字符串插值的重复问题。 - Jack jdeoel
2个回答

8

在编写更为复杂的结构时,请使用花括号进行封闭:

echo "he is {$twoDimArr['family'][1]}";

8
你应该这样做,使用花括号 {}
echo "he is {$twoDimArr['family'][1]}";


请参考字符串解析文档echo() 函数了解更多详细信息(特别是示例 #1):

// You can also use arrays  
$baz = array("value" => "foo");

echo "this is {$baz['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value  
echo 'foo is $foo'; // foo is $foo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接