Dynamic array keys

I have a line like this:

$string = 'one/two/three/four';

which I turn into an array:

$keys = explode('/', $string);

This array can have any number of elements, for example 1, 2, 5, etc.

How to assign a specific value to a multidimensional array, but use the $keys created above to determine the position at which to insert?

how

$arr['one']['two']['three']['four'] = 'value';

Sorry if the question is confusing, but I do not know how to better explain it.

+6
source share
4 answers

This is pretty nontrivial because you want to nest, but it should look something like this:

 function insert_using_keys($arr, $keys, $value){ // we're modifying a copy of $arr, but here // we obtain a reference to it. we move the // reference in order to set the values. $a = &$arr; while( count($keys) > 0 ){ // get next first key $k = array_shift($keys); // if $a isn't an array already, make it one if(!is_array($a)){ $a = array(); } // move the reference deeper $a = &$a[$k]; } $a = $value; // return a copy of $arr with the value set return $arr; } 
+13
source
 $string = 'one/two/three/four'; $keys = explode('/', $string); $arr = array(); // some big array with lots of dimensions $ref = &$arr; while ($key = array_shift($keys)) { $ref = &$ref[$key]; } $ref = 'value'; 

What does it do:

  • Using the $ref variable to track the link to the current size of $arr .
  • Loop through $keys one at a time, referring to the $key element of the current link.
  • Setting the value for the final link.
+5
source

You need to first verify that the key exists, and then assign a value. Something like this should work (unverified):

 function addValueByNestedKey(&$array, $keys, $value) { $branch = &$array; $key = array_shift($keys); // add keys, maintaining reference to latest branch: while(count($keys)) { $key = array_pop($keys); if(!array_key_exists($key, $branch) { $branch[$key] = array(); } $branch = &$branch[$key]; } $branch[$key] = $value; } // usage: $arr = array(); $keys = explode('/', 'one/two/three/four'); addValueByNestedKey($arr, $keys, 'value'); 
+1
source

it is commonplace, but:

 function setValueByArrayKeys($array_keys, &$multi, $value) { $m = &$multi foreach ($array_keys as $k){ $m = &$m[$k]; } $m = $value; } 
+1
source

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


All Articles