Reputation: 466
I has a string like as brachA-branchB-branchC
. I am trying to make it as nested array as follows
[
'name'=>'brachA',
'sub'=> [
'name'=>'brachB',
'sub'=>[
'name'=>'brachC'
]
]
]
I tried as follows (https://3v4l.org/A781D)
<?php
$nested_array = array();
$temp = &$nested_array;
$item = 'brachA-branchB-branchC';
foreach (explode('-', $item) as $key => $value) {
$temp = &$temp[$value];
}
print_r($nested_array);
Output I am getting as follows
Array
(
[brachA] => Array
(
[branchB] => Array
(
[branchC] =>
)
)
)
Any idea, how to achieve this ?
Upvotes: 1
Views: 210
Reputation: 72186
It can probably be done using a foreach
loop over the reversed array returned by explode()
but it is much easier to use a recursive function.
function makeArray(array $pieces)
{
$first = array_shift($pieces);
$array = array('name' => $first);
if (count($pieces)) {
$array['sub'] = makeArray($pieces);
}
return $array;
}
$item = 'brachA-branchB-branchC';
print_r(makeArray(explode('-', $item)));
The makeArray()
function receives an array with the string pieces. It puts the first item under the 'name'
key of a new array and invokes itself with the rest of the array to generate the array to put under the 'sub'
key. It doesn't put anything for the 'sub'
key if there is no rest (on the last call, $pieces
is array('brachC')
.
Upvotes: 3