Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a tree-like array from a loop?
    primarykey
    data
    text
    <p>Suppose I have a one-dimensional array <code>$arr</code> like this:</p> <pre><code>Array ( ['key1'] =&gt; 1 ['key2'] =&gt; 1 ['key3'] =&gt; 1 ['key4'] =&gt; 1 ) </code></pre> <p>I want to loop through <code>$arr</code> like this:</p> <pre><code>foreach($arr as $key =&gt; $a) { //$tree[????] = ????? Here is my concern } </code></pre> <p>such that, doing <code>print_r($tree)</code> produces</p> <pre><code>Array ( ['key1'] =&gt; Array ( ['key2'] =&gt; Array ( ['key3'] =&gt; Array ( ['key4'] =&gt; 1 ) ) ) ) </code></pre> <p>My concern is how to increase the dimension (not the values) of the array <code>$tree</code> inside the loop from a single dimension array <code>$numbers</code> such that <code>$tree['key1']['key2']['key3']</code> is an array and <code>$tree['key1']['key2']['key3']['key4']</code> is equal to <code>1</code>.</p> <p>Furthermore, if I have a single dimensional array <code>$foo</code> with 10 elements. I should produce another array <code>$bar</code> that expands to 10 dimensional array similar to the output above.</p> <p>What should I do inside the <code>foreach</code> loop? Or instead of using loop, is there a way to produce an output like that of above from a one dimension array?</p> <hr> <p>EDIT:</p> <blockquote> <p>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?</p> </blockquote> <p>The next element of a 1D array is a child of the previous element. So if the 1D array is like this:</p> <pre><code>Array ( ['bar'] =&gt; 1 // I don't care of the values as of the moment ['foo'] =&gt; 1 ['baz'] =&gt; 1 ) </code></pre> <p>Element <code>foo</code> should be the child of <code>bar</code>, and element <code>baz</code> should be the child of <code>foo</code> for the tree array.</p> <blockquote> <p>Ok so the actual values of everything except the last element are irrelevant?</p> </blockquote> <p>Actually all values of the 1D array is irrelevant as of this moment. I am only concerned on constructing the tree array.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload