2

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

Davide
  • 1,931
  • 2
  • 19
  • 39

1 Answers1

6
$str = "eat.fruit.apple.good";
// Set pointer at top of the array 
$arr = array();
$path = &$arr;
// Path is joined by dots
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);
splash58
  • 26,043
  • 3
  • 22
  • 34