I don’t know how to ask the question.My goal is :
convert :
JavaScript
x
$myArr = ['a', 'b', 'c', .];
into :
JavaScript
$newArr['a']['b']['c'] = 1;
Advertisement
Answer
Start with the value to be assigned, then for-loop backwards over the array:
JavaScript
$arr = [ 'a', 'b', 'c', 'd' ];
$result = 1;
for ($i = count($arr) - 1; $i >= 0; $i--) {
$result = [ $arr[$i] => $result ];
}
print_r($result);
Output:
JavaScript
Array
(
[a] => Array
(
[b] => Array
(
[c] => Array
(
[d] => 1
)
)
)
)