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)
但我不明白如何动态创建它.谢谢戴维德
$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)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |