Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should give the nodes in $container a <code>parent_container_name</code> with a null value. This will represent the top-level menu nodes. </p> <p>Next, glue your two arrays together using <code>array_merge</code>.</p> <p>Now that you have one array with common node structure, you can easily recurse downward, rendering child elements that have a <strong><code>parent_container_name</code></strong> matching the current node and repeating recursively.</p> <p>I think you want something like this:</p> <pre><code>$menuNodes; // The array of all nodes function RenderMenu() { // Grab all top-level nodes (nodes with no parent_container_name attribute) $topLevelNodes = array(); foreach ($menuNodes as $node) if ($node["parent_container_name"] == null) $topLevelNodes[] = $node; foreach ($topLevelNodes as $node) RenderMenuNode($node); } function RenderMenuNode($node) { print "&lt;div id='" . $node["attribute_value"] ."'&gt;"; $node["isRendered"] = true; // This filtering callback will discard elements that are not children or have already been rendered. function Filter($element) { global $node; return (!$element["isRendered"] &amp;&amp; $element["parent_container_name"] == $node["parent_container_name]"]); } $children = array_filter($menuNodes, 'Filter'); foreach ($children as $child) RenderMenuNode($child); print "&lt;/div&gt;"; } </code></pre> <p>I have not run or tested this code, and it could definitely be more efficient, but hopefully it points you in the right direction. Ideally you will remove rendered nodes from the menuNodes array so that you are not re-iterating over nodes unnecessarily.</p> <p>By defining your menu structure recursively in this fashion, you can have menus nested as deep as you like without having to change the code. Hope this helps!</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