如何使用字符串索引在php中动态创建数组

Dav*_*ide 2 php arrays dynamic-programming

我有一个像这样的字符串:

$str = "eat.fruit.apple.good";
Run Code Online (Sandbox Code Playgroud)

我要像这样使用这个数组:

$arr["eat"]["fruit"]["apple"]["good"] = true;
Run Code Online (Sandbox Code Playgroud)

但我不明白如何动态创建它.谢谢戴维德

spl*_*h58 5

$str = "eat.fruit.apple.good";
// Set pointer at top of the array 
$arr = array();
$path = &$arr;
// Path is joined by points
foreach (explode('.', $str) as $p) 
   // Make a next step
   $path = &$path[$p];
$path = true;
print_r($arr); // $arr["eat"]["fruit"]["apple"]["good"] = true;
Run Code Online (Sandbox Code Playgroud)

更新没有指针的Variant:

$str = "eat.fruit.apple.good";

$res = 'true';
foreach(array_reverse(explode('.', $str)) as $i) 
   $res = '{"' . $i . '":' . $res . '}'; 
$arr = json_decode($res, true);
Run Code Online (Sandbox Code Playgroud)