2016-02-03 48 views
-1
$productDetail['product']['id']='1324652'; 
$variable = "productDetail['product']['id']"; 

如何在php中使用“$ variable”打印“$ productDetail ['product'] ['id']”的值?如何通过变量的值打印数组值?

+0

你的意思是数组元素的值赋给'$ variable'?这只是'$ variable = $ productDetail ['product'] ['id'];打印$变量;' – SaschaM78

+0

它与我们在下面的例子中使用$$ Lke相同** $ a ='name'; $$ a =“Paul”; echo $ name; 输出是Paul ** –

+0

对不起,您的评论不符合您的初始问题,您能否更好地解释您真正尝试实现的目标? – SaschaM78

回答

0

不是好办法,JUSE给大家一个参考

$productDetail['product']['id']='1111'; 
 
$productDetail['product']['idd']['id']='2222'; 
 

 
$variable = "productDetail['product']['idd']['id']"; 
 
$variable_new = parse_variable($variable); 
 

 
$re = $$variable_new[0]; 
 
if(count($variable_new) > 1){ 
 
    // loop $variable_new to get next data, one by one 
 
\t for($i = 1; $i < count($variable_new); $i++){ 
 
\t \t $re = $re[$variable_new[$i]]; 
 
\t } 
 
} 
 
var_dump($re);exit; 
 

 
// parse variable to array 
 
function parse_variable($variable){ 
 
\t // return $variable if there no [ 
 
\t if(!strpos($variable, '[')){ 
 
\t \t return array(0 => $variable); 
 
\t } 
 

 
\t // parse variable to array 
 
\t $variables = explode('[', $variable); 
 
\t $new_variables = ''; 
 
\t foreach($variables as $variable){ 
 
\t \t $variable = str_ireplace("'", '', $variable); 
 
\t \t $variable = str_ireplace("]", '', $variable); 
 
\t \t $new_variables[] = $variable; 
 
\t } 
 
\t return $new_variables; 
 
}

+0

谢谢suibber,这是我真正想要的完美。但字符串输入是动态的,来自用户输入,所以我如何使它像使用动态可能输入“productDetail ['product'] ['id']”或只是“productDetail ['product']”或“productDetail [''产品'] ['id'] ['id']“ –

+0

我编辑了我的答案,您可以循环用户输入以获取数据 – suibber