I have a string (pattern):

$pattern = 'config.images.0.width'; 

I need to build an array dynamically based on this pattern in order to get the following:

 $arr['config']['images'][0]['width'] = 500; $width = $arr['config']['images'][0]['width']; 

As you can see, using "hands" is not a problem to do, but how to do it dynamically?

2 answers 2

 $pattern = 'config.images.0.width'; $value = 400; $keys = explode('.', $pattern); $arr=[]; function addInner($keys, &$arr, $value){ $key = array_shift($keys); $arr[$key] = null; if(empty($keys)) { $arr[$key] = $value; return; } addInner($keys, $arr[$key], $value); } addInner($keys, $arr, $value); 

sandbox

    Pretty simple and short version:

     function getValueByPath($path, $array) { $tmp = &$array; foreach($path as $key) { $tmp =& $tmp[$key]; } return $tmp; } //----------------------------------------- // Пример использования // // Входные данные $arr = ['f1' => 1, 'config' => [ 'videos' => 'http://video.ru', 'images' => [ ['width' => 100, 'height' => 80 ], ['width' => 666, 'height' => 1 ], ['width' => 0, 'height' => 0 ], ] ], 'f3' => null ]; // путь $key = 'config.images.0.width'; $path = explode('.', $key); // output $result = getValueByPath($path, $arr); echo $result; // 100 

    http://sandbox.onlinephpfunctions.com/code/bd93fccc8070b46ec246e2aa460ddadc1bd117e1

    Suspended to https://stackoverflow.com/a/27930028/6104996


    The point is that with each cycle pass in tmp , the value by key from the previous iteration is added. At the initial iteration, tmp corresponds to the original array.

    • 0 step (before cycle):

       $tmp = ['f1' => 1, 'config' => [ 'videos' => 'http://video.ru', 'images' => [ ['width' => 100, 'height' => 80 ], ['width' => 666, 'height' => 1 ], ['width' => 0, 'height' => 0 ], ] ], 'f3' => null ]; 
    • 1 iteration ( $tmp['config'] )

       $tmp = ['videos' => 'http://video.ru', 'images' => [ ['width' => 100, 'height' => 80 ], ['width' => 666, 'height' => 1 ], ['width' => 0, 'height' => 0 ], ] ]; 
    • 2 iteration ( $tmp['images'] )

       $tmp = [ ['width' => 100, 'height' => 80 ], ['width' => 666, 'height' => 1 ], ['width' => 0, 'height' => 0 ], ]; 
    • 3 iteration ( $tmp[0] )

       $tmp = ['width' => 100, 'height' => 80 ]; 
    • 4 iteration ( $tmp['width'] )

       $tmp = 100;