如何通过数组值引用嵌套的 class 值
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 是行不通的。也不知道数组长度。
正如我在评论中指出的那样,您需要按预期访问 object/arrays。
他们的符号如下;
- 对象:
->
- 数组:
[]
因此,使用您生成的 $data
数组,您必须访问 object/array 组合:
echo $data->s[2];
并且如果您要访问初始 test/test2
迭代(设置为对象 (->
)),则您需要访问它作为一个对象:
echo $data->test->test2;
想通了:
$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
我认为解释我的问题的最好方法是举个例子。假设我有以下对象。
$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 是行不通的。也不知道数组长度。
正如我在评论中指出的那样,您需要按预期访问 object/arrays。 他们的符号如下;
- 对象:
->
- 数组:
[]
因此,使用您生成的 $data
数组,您必须访问 object/array 组合:
echo $data->s[2];
并且如果您要访问初始 test/test2
迭代(设置为对象 (->
)),则您需要访问它作为一个对象:
echo $data->test->test2;
想通了:
$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