Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an tree that has no single top using associative arrays
    text
    copied!<p>I've an array that has around 300 items. There are 5 properties per item. Some items have a parent item. the nested items need to be able to scale to unlimited nesting.</p> <p>I need to organise the array so that all items that have a parent are within the parent item <code>children</code> property. The <code>child</code> will have <code>children</code></p> <p>I can create an associative array that makes the first 2 levels. The top parent items and it's children.</p> <p>Now my problem comes when I am trying to create unlimited nesting. I can't see a way to automatically create a method that will adapt to multiple nesting levels and put the information to where it should be nested to. </p> <p>I've never had to build such a tree and performance is crucial. Could anyone give me guidance on how could I achieve what I intend to achieve? I would really appreciate it</p> <p>Edit: my issue is if i have to use recursion, not how to split what i've just done into 1 separate method.</p> <pre><code> $tree = array(); /* * $three = array( array( 'id','parent_id','displayAs', 'children' ) ) */ foreach ( $taxonomyFullList as $firstLevel ) { // Get all if( (int)$firstLevel['parent_id'] == 0 ) { $tree[] = array( 'id' =&gt; $firstLevel['id'], 'parent_id' =&gt; $firstLevel['parent_id'], 'displayAs' =&gt; $firstLevel['displayAs'], 'type' =&gt; $firstLevel['type'], 'children' =&gt; array() ); $key = array_search( $firstLevel,$taxonomyFullList ); unset( $taxonomyFullList[$key] ); } } foreach ( $taxonomyFullList as $secondLevel ) { foreach ( $tree as $firstTreeLevel ) { if( (int)$secondLevel['parent_id'] === (int)$firstTreeLevel['id'] ) { $newArray = array( 'id' =&gt; $secondLevel['id'], 'parent_id' =&gt; $secondLevel['parent_id'], 'displayAs' =&gt; $secondLevel['displayAs'], 'type' =&gt; $secondLevel['type'], 'children' =&gt; array() ); $key = array_search( $firstTreeLevel, $tree ); array_push( $tree[$key]['children'], $newArray ); $taxonomyFullListKey = array_search( $secondLevel,$taxonomyFullList ); unset( $taxonomyFullList[$taxonomyFullListKey] ); } } } </code></pre>
 

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