0

我正在尝试传递存储在变量中的关联数组的索引:

$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")

如何正确使用变量来访问上面示例中提到的值?注意:将它们包装到大括号中(即复杂的语法)在这两种情况下都不起作用。

4

2 回答 2

0

我假设您手动键入了该['one']['two']部分,并且没有理由让它看起来像那样。

迄今为止最简单的方法是分解数组索引并循环它们,然后“挖掘”到数组中。

$a = array( 
 'one' => array('one' => 11, 'two' =>12),
 'two' => array('one' => 21, 'two' => 22)
);    
$s = "one,two";

$res = $a;
foreach(explode(",", $s) as $item){
    $res = $res[$item];
}

echo $res; // in this case echo works. But you should perhaps have if array print_r

https://3v4l.org/LeUFW

如果你确实有一个这样的两个,那么你可以把它变成一个这样的数组:

$s = "['one']['two']";
$s = explode("][", str_replace("'", "", trim($s, "[]")));
// $s is now an array ['one', 'two']

https://3v4l.org/YUjbn

于 2020-01-13T20:54:32.163 回答
-1

唯一的解决方案似乎是eval() 如果您信任以下内容$s

eval( 'echo $a'.$s.';' );
于 2020-01-13T20:55:27.290 回答