我正在尝试传递存储在变量中的关联数组的索引:
$a = array(
'one' => array('one' => 11, 'two' =>12),
'two' => array('one' => 21, 'two' => 22)
);
$s = "['one']['two']"; // here I am trying to assign keys to a variable for a future use
echo $a[$s]; // this usage gives error Message: Undefined index: ['one']['two']
echo $a['one']['two']; // this returns correct result (12)
我试图在对象中做同样的事情:
$a = array(
'one' => (object)array('one' => 11, 'two' =>12),
'two' => (object)array('one' => 21, 'two' => 22)
);
$a = (object)$a; // imagine that I receive this data from a JSON (which has much sophisticated nesting)
$s = 'one->two'; // I want to access certain object property which I receive from somewhere, hence stored in a variable
echo $a->$s; // produces error. Severity: Notice Message: Undefined property: stdClass::$one->two
echo $a->one->two; // gives correct result ("12")
如何正确使用变量来访问上面示例中提到的值?注意:将它们包装到大括号中(即复杂的语法)在这两种情况下都不起作用。