I have a JSON object that I try to modify. So I created the following function. I firstly deserialize the JSON object and then given the array and the path that I want to change I modify the value.
function setInDict($arr, $path, $value){
switch(sizeof($path)){
case 1:
$arr[$path[0]] = $value;
break;
case 2:
$arr[$path[0]][$path[1]] = $value;
break;
case 3:
$arr[$path[0]][$path[1]][$path[2]] = $value;
break;
case 4:
$arr[$path[0]][$path[1]][$path[2]][$path[3]] = $value;
break;
case 5:
$arr[$path[0]][$path[1]][$path[2]][$path[3]][$path[4]] = $value;
break;
}
return $arr;
}
I tried a lot of things(recursion, &arr) to make it work dynamically but my PHP experience is limited and I cant make it to work.
Is there a clean way to do this. Is there something alternative that I can try?
For example I have the following JSON and I want to modify subsubkey to value 2
{
"key":{
"subkey":{
"subsubkey":3
}
}
}
I deserialize it using json_decode($json, true); and I create the $path array which would be
['key', 'subkey', 'subsubkey']
$arr, $path, $value?