Jump to content

what would be the most efficient way to parse this array into a multi-dim array


emehrkay

Recommended Posts

[code]
Array
(
    [0] => stdClass Object
        (
            [navigation_id] => 1
            [parent_nav_id] => 0
            [display_name] => Music
            [nav_link] => #
        )

    [1] => stdClass Object
        (
            [navigation_id] => 2
            [parent_nav_id] => 0
            [display_name] => Members
            [nav_link] => #
        )

    [2] => stdClass Object
        (
            [navigation_id] => 3
            [parent_nav_id] => 2
            [display_name] => Users
            [nav_link] => #
        )

    [3] => stdClass Object
        (
            [navigation_id] => 4
            [parent_nav_id] => 2
            [display_name] => Top 8 Charts
            [nav_link] => #
        )

    [4] => stdClass Object
        (
            [navigation_id] => 5
            [parent_nav_id] => 3
            [display_name] => Message
            [nav_link] => #
        )

    [5] => stdClass Object
        (
            [navigation_id] => 6
            [parent_nav_id] => 3
            [display_name] => Search
            [nav_link] => #
        )

)
[/code]


I am making a menu system and i have a navigation table. i have the highest level elements' parent_nav_id set to zero and their children's parent_nav_id set to their navigation_id and so on.

I could easily make the multi-dimm array by using two seperate queries (but they'd be run the number of elements in the table), but id rather have less processing work on that end and have it done with php.

How could I loop through this array creating arrays of items that have a similar parent_nav_id and place those arrays in that parent_nav_id's array and so on?

Thanks
Instead of creating a new array, you could just use the one you already have and use something like this to create your links:

[code]<?php
foreach ($links as $link) {
    if ($link['parent_nav_id']==0) {
        echo "<b><a href=\"".$link['nav_link']."\">".$link['display_name']."</a></b><br>";
        foreach ($links as $sublink) {
            if ($sublink['parent_nav_id']==$link['navigation_id']) {
                echo " - <a href=\"".$link['nav_link']."\">".$sublink['display_name']."</a><br>";
            }
        }
    }
}
?>[/code]

However, if you really want to rebuild the array, you could do this:
[code]<?php
foreach ($links as $link) {
    if ($link['parent_nav_id']==0) {
        $newlinks[$link['navigation_id']] = $link;
    } else {
        $newlinks[$link['parent_nav_id']]['sublinks'][] = $link;
    }
}
?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.