array("c", "d" => array("e", "f")), "g", "h" => array("f"))...">

How to dynamically access values ​​in a multi-parameter array

$first = array("a", "b" => array("c", "d" => array("e", "f")), "g", "h" => array("f")); $second = array("b", "d", "f"); $string = "foobar"; 

Given the code above, how can I set the value in $first in the indices defined in $second to the contents of $string ? The value for this example should be $first["b"]["d"]["f"] = $string; , but the contents of $second and $first can be any length. $second will always be one-dimensional. Here is what I tried, which didn't seem to work as planned:

 $key = ""; $ptr = $first; for($i = 0; $i < count($second); $i++) { $ptr &= $ptr[$second[$i]]; $key = key($ptr); } $first[$key] = $string; 

This will do $first["f"] = $string; instead of the correct multidimensional indexes. I thought using key would find a location in the array, including levels that it had already pushed down.

How can I access the corresponding keys dynamically? I could manage this if the number of measurements was static.

EDIT: Also, I would like to make a method that does not use eval .

+6
source share
1 answer

It is a little harder than that. You must initialize each level if it does not already exist. But your current problems:

  • The array you want to add the value to is in $ptr , not $first .
  • $x &= $y is shorthand for $x = $x & $y (bitwise AND). You want x = &$y (assign by reference).

This should do it:

 function assign(&$array, $keys, $value) { $last_key = array_pop($keys); $tmp = &$array; foreach($keys as $key) { if(!isset($tmp[$key]) || !is_array($tmp[$key])) { $tmp[$key] = array(); } $tmp = &$tmp[$key]; } $tmp[$last_key] = $value; unset($tmp); } 

Using:

 assign($first, $second, $string); 

Demo

+9
source

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


All Articles