PHP: reorder array to show hierarchy
<p>How can I turn the first array in to the second one? The goal is to create an array that shows the hierarchy, based on location_id and parent_id. Each location_name should be in an array of which the key is its parent_id.</p>

<p>Ignore the values I gave to location_name. No value for parent_id == NULL, these are the top level items.</p>

<p>First array:</p>

<pre><code>    Array
    (
        [0] =&gt; stdClass Object
            (
                [location_id] =&gt; 1
                [location_name] =&gt; Town 1
                [parent_id] =&gt; 
            )

        [1] =&gt; stdClass Object
            (
                [location_id] =&gt; 2
                [location_name] =&gt; Town 1.1
                [parent_id] =&gt; 
            )

        [2] =&gt; stdClass Object
            (
                [location_id] =&gt; 3
                [location_name] =&gt; Town 1.2
                [parent_id] =&gt; 1
            )

        [3] =&gt; stdClass Object
            (
                [location_id] =&gt; 4
                [location_name] =&gt; Town 1.3
                [parent_id] =&gt; 1
            )

        [4] =&gt; stdClass Object
            (
                [location_id] =&gt; 5
                [location_name] =&gt; town 1.1.1
                [parent_id] =&gt; 2
            )

        [5] =&gt; stdClass Object
            (
                [location_id] =&gt; 6
                [location_name] =&gt; Town 1.1.2
                [parent_id] =&gt; 3
            )
);
</code></pre>

<p>Resulting array should be:</p>

<pre><code>Array(
        'Town 1' = array(
            'town 1.2',
            'town 1.3' = array(
                 'town 1.1.2'
             )
        ),
        'Town 2' = array(
             'town 1.1.1'
        )
    );
</code></pre>

<p>EDIT: working solution based on Rijk's answer</p>

<pre><code>function _order_locs($parent, $array)
    {
        $return = array();
        foreach ( $array as $town )
        {
            if ( $town-&gt;parent_id == $parent )
            {
                $set = $this-&gt;_order_locs( $town-&gt;location_id, $array );               
                if( $this-&gt;_menu_is_parent($town-&gt;location_id, $array) ) $return[$town-&gt;location_name] = $set;
                else $return[] = $town-&gt;location_name;            
            }
        }

        return $return;
    }

    function _menu_is_parent($id, $array)
    {
        foreach( $array as $a )
        {
            if( $a-&gt;parent_id == $id ) return TRUE;
        }
    }
</code></pre>
