我正在尝试通过描述数组路径的字符串(如 )从多维数组中检索项目first.second.third
。
我选择了这里显示的方法(也可以在 ideone 上找到):
<?php
// The path into the array
$GET_VARIABLE = "a.b.c";
// Some example data
$GLOBALS["a"]= array("b"=>array("c"=>"foo"));
// Construct an accessor into the array
$variablePath = explode( ".", $GET_VARIABLE );
$accessor = implode( "' ][ '", $variablePath );
$variable = "\$GLOBALS[ '". $accessor . "' ]";
// Print the value for debugging purposes (this works fine)
echo $GLOBALS["a"]["b"]["c"] . "\n";
// Try to evaluate the accessor (this will fail)
echo $$variable;
?>
当我运行脚本时,它将打印两行:
foo
PHP Notice: Undefined variable: $GLOBALS[ 'a' ][ 'b' ][ 'c' ] in ...
那么,为什么这不能正确评估呢?