How dynamically create array in php with string index [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-13 15:24:29

问题


I've a string like this:

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

I've to use this array like this:

$arr["eat"]["fruit"]["apple"]["good"] = true;

But I don't understand how can I create it dynamically. Thanks Davide


回答1:


$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 Variant without pointer:

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

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


来源:https://stackoverflow.com/questions/37659106/how-dynamically-create-array-in-php-with-string-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!