I have a nested object that was created using json_decode and that I want to dynamically loop through in PHP and alter specific values within it. The path to the key I want to alter is stored in an indexed array that I pass to my function, where the last item in the array contains the key.
The array containing the path to the key looks like this:
array(3) {
[0]=>
string(6) "level1"
[1]=>
string(6) "level2"
[2]=>
string(6) "level3"
}
My object $obj
looks like this:
{
"level1": {
"level2": {
"level3": "value"
}
}
}
When it's all objects, inside my for loop I can do this:
for($i = 0; $i < count($array); $i++) {
$obj = $obj->{$array[$i]};
if($i == count($array)-1) $obj = $value;
}
=> thus, altering the original object.
However, I'm stuck at inserting a new value into an indexed array that is part of my JSON object, using the method above. Consider that 'level3' in the following example represents an indexed array inside my object.
{
"level1": {
"level2": {
"level3": []
}
}
}
If I do:
for($i = 0; $i < count($array); $i++) {
$obj = $obj->{$array[$i]};
if($i == count($array)-1) {
if(gettype($obj) == 'object') $obj = $value;
else if(gettype($obj) == 'array') array_push($obj, $value);
}
}
When I var_dump
the altered array inside the for loop, I get the expected results. However this way, the original array inside my object remains untouched. How can I achieve the array being altered in my object instead of just in local scope?
It seems that I am only able to achieve that behavior only if I access it staticly, like this: array_push($obj->level1->level2->level3, $value);
But I can't think of a dynamic way of achieving this.
I hope I made it all clear and anyone has a possible solution to this problem.