Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Recursive entities are never easy, especially if you are starting out with PHP.</p> <p>The following is a short function that avoids the need for using a recursive function by using php references instead. References can be confusing, as can recursion. The best advice is to read up and try a few things out in order to work out how they behave.</p> <p>The following works using a stack that keeps track of the levels, and keeps referring back to the last level to find the latest parent.</p> <pre><code>function stackItems( $items ){ $level = 0; $return = array(); $stack = array(&amp;$return); foreach ( $items as $key =&gt; $item ) { while ( $level &gt;= $item['level'] ) { unset($stack[$level--]); } $parent = &amp;$stack[$level]; if ( !isset($parent['children']) ) { $parent['children'] = array(); } $parent['children'][] = &amp;$items[$key]; if ( $item['level'] &gt; $level ) { $level = $item['level']; $stack[$level] = &amp;$items[$key]; } } return $return['children']; } </code></pre> <p>With comments version:</p> <pre><code>function stackItems( $items ){ $level = 0; $return = array(); /// build our stack with our return array as first item $stack = array(&amp;$return); /// step each item foreach ( $items as $key =&gt; $item ) { /// if our next item is lower down than current /// level, drop the stack down. while ( $level &gt;= $item['level'] ) { /// we may as well unset to clear memory unset($stack[$level--]); } /// create a shortcut reference to our parent on the stack $parent = &amp;$stack[$level]; /// to avoid warnings create the children array first if ( !isset($parent['children']) ) { $parent['children'] = array(); } /// now add ourselves to the current parent on the stack $parent['children'][] = &amp;$items[$key]; /// if our current item is higher level than current, add to /// the stack ready to be treated as the next parent. if ( $item['level'] &gt; $level ) { /// level ourselves to the current item $level = $item['level']; /// store in the stack a reference to item $stack[$level] = &amp;$items[$key]; } } /// return the first set of children as there seems /// to be only one level 1 item. return $return['children']; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
    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