Suppose I have a one-dimensional array $arr like this:
Array
(
['key1'] => 1
['key2'] => 1
['key3'] => 1
['key4'] => 1
)
I want to loop through $arr like this:
foreach($arr as $key => $a) {
//$tree[????] = ????? Here is my concern
}
such that, doing print_r($tree) produces
Array
(
['key1'] => Array
(
['key2'] => Array
(
['key3'] => Array
(
['key4'] => 1
)
)
)
)
My concern is how to increase the dimension (not the values) of the array $tree inside the loop from a single dimension array $numbers such that $tree['key1']['key2']['key3'] is an array and $tree['key1']['key2']['key3']['key4'] is equal to 1.
Furthermore, if I have a single dimensional array $foo with 10 elements. I should produce another array $bar that expands to 10 dimensional array similar to the output above.
What should I do inside the foreach loop? Or instead of using loop, is there a way to produce an output like that of above from a one dimension array?
EDIT:
OK well you obviously need some kind of recursive function, but can you explain how you know that key2 should be a child of key1, key3 should be a child of key2 etc based on the data you show?
The next element of a 1D array is a child of the previous element. So if the 1D array is like this:
Array
(
['bar'] => 1 // I don't care of the values as of the moment
['foo'] => 1
['baz'] => 1
)
Element foo should be the child of bar, and element baz should be the child of foo for the tree array.
Ok so the actual values of everything except the last element are irrelevant?
Actually all values of the 1D array is irrelevant as of this moment. I am only concerned on constructing the tree array.
key2should be a child ofkey1,key3should be a child ofkey2etc based on the data you show?