Setting a value in a multidimensional array using an array of keys

In connection with this question, I asked before: Searching for keys of a multidimensional array using another array

I need a way to set a value in a multidimensional array (up to 6 levels) using a separate array containing the keys to use.

eg.

$keys = Array ('A', 'A2', 'A22', 'A221'); $cats[A][A2][A22][A221] = $val; 

I tried to write a clumsy switch with little success ... is there a better solution?

 function set_catid(&$cats, $keys, $val) { switch (count($keys)) { case 1: $cats[$keys[0]]=$val; break; case 2: $cats[$keys[0]][$keys[1]]=$val; break; case 3: $cats[$keys[0]][$keys[1]][$keys[2]]=$val; break; etc... } } 
+6
source share
3 answers

try the following:

 function set_catid(&$cats, $keys, $val) { $ref =& $cats; foreach ($keys as $key) { if (!is_array($ref[$key])) { $ref[$key] = array(); } $ref =& $ref[$key]; } $ref = $val; } 
+1
source
 function insertValueByPath($array, $path, $value) { $current = &$array; foreach (explode('/', $path) as $part) { $current = &$current[$part]; } $current = $value; return $array; } $array = insertValueByPath($array, 'A/B/C', 'D'); // => $array['A']['B']['C'] = 'D'; 

You can also use an array for $path by simply dropping the explode call.

+1
source

You must use links.

In foreach, we move deeper from key to key. Var $ temp is a reference to the current element of the $ cat array. At the end, temp is the element we need.

  <?php function set_catid(&$cats, $keys, $val) { $temp = &$cats; foreach($keys as $key) { $temp = &$temp[$key]; } $temp = $val; } $cats = array(); $keys = Array ('A', 'A2', 'A22', 'A221'); set_catid($cats, $keys, 'test'); print_r($cats); ?> 
0
source

Source: https://habr.com/ru/post/902333/


All Articles