Ugly editing value on PHP nested array -


i have json object try modify. created following function. firstly deserialize json object , given array , path want change modify 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 lot of things(recursion, &arr) make work dynamically php experience limited , cant make work.

is there clean way this. there alternative can try?

for example have following json , want modify subsubkey value 2

{     "key":{       "subkey":{         "subsubkey":3     }   } } 

i deserialize using json_decode($json, true); , create $path array

['key', 'subkey', 'subsubkey'] 

if don't want create new updated array recursively can use references. following code walks through given array , on each iteration changes reference nested array until reaches field want change.

function setindict(array $array, array $path, $value) {     if (!$path) {         return $array;     }      $found = &$array;     foreach ($path $field) {         if (!isset($found[$field]) || !array_key_exists($field, $found)) {             throw new \invalidargumentexception("there no nested field '$field' in given array");         }          $found = &$found[$field];     }      $found = $value;      return $array; } 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -