如何通过变量的值来打印数组值?

时间:2016-02-03 10:20:23

标签: php arrays variables

$productDetail['product']['id']='1324652'; 
$variable = "productDetail['product']['id']";

我如何打印" $ productDetail ['产品'] [' id']"的价值?使用" $ variable"在PHP吗?

1 个答案:

答案 0 :(得分: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
	for( $i = 1; $i < count($variable_new); $i++ ){
		$re = $re[$variable_new[$i]];
	}
}
var_dump( $re );exit;

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

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