PHP: concatenation of multidimensional array elements

梦想与她 提交于 2019-12-13 16:45:26

问题


I want to concatenate one element of a multidimensional array with some strings.

<?
$string1 = 'dog';
$string2 = array
           (
            'farm' => array('big'=>'cow', 'small'=>'duck'),
            'jungle' => array('big'=>'bear', 'small'=>'fox')
           );
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>

By using this syntax for $string, I get:

dog Array[big] cat

I would like not to use the alternate syntax

$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;

which works.

What's wrong with "$string1 $string2[$type][$size] $string3"?


回答1:


Use the "complex syntax":

$string = "$string1 {$string2[$type][$size]} $string3";

PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.

See PHP - Variable parsing.




回答2:


I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:

$string = implode(' ', array($string1, $string2[$type][$size], $string3));



回答3:


Use this:

$string = "$string1 {$string2[$type][$size]} $string3";


来源:https://stackoverflow.com/questions/4886388/php-concatenation-of-multidimensional-array-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!