简体   繁体   English

PHP:多维数组元素的串联

[英]PHP: concatenation of multidimensional array elements

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: 通过对$ string使用此语法,我得到:

dog Array[big] cat 狗Array [big]猫

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"? “ $ string1 $ string2 [$ type] [$ size] $ string3”有什么问题?

Use the "complex syntax": 使用“复杂语法”:

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

PHP's variable parsing is quite simple. PHP的变量解析非常简单。 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 . 参见PHP-变量解析

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));

用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM