title: Flat array to multidimensional array
body: <p>I have a flat array full of navigation menu items in WP. Each item knows its parent, but none of them seem to know if they have children.</p>
  
  <pre><code>            Array
  (
      [0] =&gt; stdClass Object
          (
              [ID] =&gt; 22
              [menu_item_parent] =&gt; 0
          )
      [1] =&gt; stdClass Object
          (
              [ID] =&gt; 108
              [menu_item_parent] =&gt; 22
          )
      [2] =&gt; stdClass Object
          (
              [ID] =&gt; 117
              [menu_item_parent] =&gt; 108
          )
      [3] =&gt; stdClass Object
          (
              [ID] =&gt; 118
              [menu_item_parent] =&gt; 108
          )
      [4] =&gt; stdClass Object
          (
              [ID] =&gt; 106
              [menu_item_parent] =&gt; 22
          )
      [5] =&gt; stdClass Object
          (
              [ID] =&gt; 119
              [menu_item_parent] =&gt; 106
          )
      [6] =&gt; stdClass Object
          (
              [ID] =&gt; 120
              [menu_item_parent] =&gt; 106
          )
      [7] =&gt; stdClass Object
          (
              [ID] =&gt; 23
              [menu_item_parent] =&gt; 0
          )
  )
  </code></pre>
  
  <p>I've tried approaching it with conditional logic a few different ways (and each time hard-coding values which isn't ideal), but I keep coding myself into a mess. How can I iterate over the array to produce a result like this?</p>
  
  <pre><code>&lt;ul&gt;
      &lt;li&gt;22
          &lt;ul class="child"&gt;
              &lt;li&gt;108
                  &lt;ul class="grandchild"&gt;
                      &lt;li&gt;117&lt;/li&gt;
                      &lt;li&gt;118&lt;/li&gt;
                  &lt;/ul&gt;
              &lt;/li&gt;
              &lt;li&gt;106
                  &lt;ul class="grandchild"&gt;
                      &lt;li&gt;119&lt;/li&gt;
                      &lt;li&gt;120&lt;/li&gt;
                  &lt;/ul&gt;
              &lt;/li&gt;           
          &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;23&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>