PHP,创建动态变量

时间:2017-05-02 作者:Nikhil Gupta

有没有什么方法可以在php中声明动态变量。例如,我使用for循环,变量名为$message。我想在变量名的末尾添加一些动态数据。代码如下

foreach ($quant as $quantity) {
            $message.$quantity[\'type\'] =  \'Listing ID : \'.$quantity[\'product_id\'].\' With Quantity: \'.$quantity[\'quantity\'].\'MT, State- \'.$quantity[\'state_name\'].\' and Coal type-\'.$quantity[\'coal_type\'].\'<br>\';
        }
因此,如果$quantity[\'type\']=1,那么变量名应该是$message1,依此类推。目前我正在尝试连接,但这是错误的。请告诉我如何更正。提前感谢

2 个回复
SO网友:Nikhil Gupta

在做了一点研究之后,我自己找到了解决办法。

下面是显示如何执行此操作的代码

foreach ( $quant as $quantity ) {
    $test  = \'message\' . $quantity[\'type\'];
    $test .=  \'Listing ID : \' . $quantity[\'product_id\'] 
        . \' With Quantity: \'  . $quantity[\'quantity\'] 
        . \'MT, State- \'       . $quantity[\'state_name\'] 
        . \' and Coal type-\'   . $quantity[\'coal_type\'];
}
现在$message1将打印结果。

SO网友:Gavin

我想您自己的解决方案是可行的(双倍$$),但通常您是这样做的:

$quantity[\'type\'] = 1;
${\'message\' . $quantity[\'type\']} = \'hello\';
echo $message1; // hello

相关推荐

无法在模板函数.php中使用IS_HOME

我试图在标题中加载一个滑块,但只在主页上加载。如果有帮助的话,我正在使用Ultralight模板。我正在尝试(在template functions.php中)执行以下操作:<?php if ( is_page( \'home\' ) ) : ?> dynamic_sidebar( \'Homepage Widget\' ); <?php endif; ?> 但这行不通。现在,通过快速的google,我似乎需要将请