如何通过数组值引用嵌套的类值


how to refrence a nested class value by array value

我认为解释我的问题最好的方法是举一个例子。假设我有以下物体。

$data=new stdClass;
$data->test=new stdClass;
$data->test->test2=6;
$data->s=array('b',6,7);

我想知道如何在给定键值作为数组的对象中读取或更改任何值。

我知道下面是行不通的:

function doSomething($inputArray1,$inputArray2) {
    $data[  $inputArray1   ]; //6
    $data[  $inputArray2   ]=4; //was array('b',6,7);
}
//someone else provided
doSomething( array('test','test2')  , array('s')  );

更改为明确我不知道数组的值,所以使用用$data->test->test2;得到6是行不通的。也不知道数组的长度

figure out:

$parts=array('test','test2');

$ref=&$data;
foreach($parts as $part) {
    if (is_array($ref)) {
        $ref=&$ref[$part]; //refrence next level if array
    } else {
        $ref=&$ref->$part; //refrence next level if object
    }
}
echo $ref; //show value refrenced by array
$ref=4; //change value refrenced by array(surprised this works instead of making $ref=4 and breaking the refrence)
unset($ref); //get rid of refrence to prevent accidental setting.  Thanks @mpyw

正如我在注释中指出的,您需要按预期访问对象/数组。它们的符号如下:

  • 对象:->
  • Array: []

因此,使用您生成的$data数组,您必须像这样访问对象/数组组合:

echo $data->s[2];

<一口>/例子演示

如果要访问初始test/test2迭代(设置为对象(->)),则需要将其作为对象访问:

echo $data->test->test2;