我有这样的字符串:
$str = "eat.fruit.apple.good";
我可以像这样使用这个数组:
$arr["eat"]["fruit"]["apple"]["good"] = true;
但我不明白如何动态创建它。 谢谢 的Davide
答案 0 :(得分: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;
UPDATE 没有指针的变体:
$str = "eat.fruit.apple.good";
$res = 'true';
foreach(array_reverse(explode('.', $str)) as $i)
$res = '{"' . $i . '":' . $res . '}';
$arr = json_decode($res, true);