Note that there are some explanatory texts on larger screens.

plurals
  1. POFlat PHP Array to Hierarchy Tree
    text
    copied!<p>I have an array with the following keys</p> <pre><code>id parent_id name </code></pre> <p>A sample array:</p> <pre><code>array(7) { [0]=&gt; array(3) { ["id"]=&gt; string(1) "4" ["parent_id"]=&gt; string(1) "0" ["name"]=&gt; string(16) "Top Level Page 4" } [1]=&gt; array(3) { ["id"]=&gt; string(1) "5" ["parent_id"]=&gt; string(1) "1" ["name"]=&gt; string(19) "Second Level Page 1" } [2]=&gt; array(3) { ["id"]=&gt; string(1) "6" ["parent_id"]=&gt; string(1) "2" ["name"]=&gt; string(19) "Second Level Page 2" } [3]=&gt; array(3) { ["id"]=&gt; string(1) "7" ["parent_id"]=&gt; string(1) "5" ["name"]=&gt; string(18) "Third Level Page 1" } [4]=&gt; array(3) { ["id"]=&gt; string(1) "3" ["parent_id"]=&gt; string(1) "0" ["name"]=&gt; string(16) "Top Level Page 3" } [5]=&gt; array(3) { ["id"]=&gt; string(1) "2" ["parent_id"]=&gt; string(1) "0" ["name"]=&gt; string(16) "Top Level Page 2" } [6]=&gt; array(3) { ["id"]=&gt; string(1) "1" ["parent_id"]=&gt; string(1) "0" ["name"]=&gt; string(16) "Top Level Page 1" } } </code></pre> <p>What I would like to do is display a hierarchy tree using this array, the code I have at the moment is producing: </p> <pre><code>Top Level Page 4 --Second Level Page 1 ---Second Level Page 2 ----Third Level Page 1 Top Level Page 3 Top Level Page 2 Top Level Page 1 </code></pre> <p>Ideally I need to produce the below result but with unlimited levels:</p> <pre><code>Top Level Page 4 -Second Level Page 1 -Second Level Page 2 --Third Level Page 1 Top Level Page 3 Top Level Page 2 Top Level Page 1 </code></pre> <p>The code I have so far is:</p> <pre><code>$level = 1; foreach ($data as $row) { if ($row['parent_id'] == 0) { echo $row['name'] . '&lt;br/&gt;'; } else { $level++; foreach ($data as $m) { if ($m['parent_id'] === $row['parent_id']) { $c = 0; $append = ''; while ($c &lt; $level) { $append.="-"; $c++; } echo $append . $row['name'] . '&lt;br/&gt;'; } } } } } </code></pre> <p>If anyone could give me some pointers on how to achieve this it would be much appreciated.</p> <p>I found a solution here: <a href="https://stackoverflow.com/questions/14613546/create-nested-list-from-php-array-for-dropdown-select-field?rq=1">Create nested list from PHP array for dropdown select field</a></p>
 

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