2016-06-06 4 views

답변

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); 
+0

매우 깔끔한 솔루션! –

+0

전혀 나쁘지 않다 ... – DonCallisto

+0

정말 천재 야. 고마워. 포인터를 사용하지 않으려면 어떻게해야합니까? – Davide

관련 문제