multilevel ul with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
heltr
Forum Newbie
Posts: 1
Joined: Wed Oct 07, 2009 8:19 am

multilevel ul with PHP

Post by heltr »

hi, I'm pretty new to PHP and I need help with multilevel unordered list.
I retrieve data from 2 tables of database and get an array which I need to tranform somehow into multilevel unordered list:

Code: Select all

try
            {
                $dbh = new PDO($dsn, $user, $password);
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $sql = 'SELECT BookGroups.GroupID, GroupName, BookID, BookName FROM BookGroups, BookEntries WHERE BookGroups.GroupID = BookEntries.GroupID';
                $stmt = $dbh->prepare($sql);
                $stmt->execute();
                                                   while ($item=$stmt->fetch(PDO::FETCH_ASSOC)) { 
                    print_r($item);} ....
That's the piece of code I have,and as a result of it I get number of arrays like:

Code: Select all

Array
(
    [GroupID] => 1
    [GroupName] => Fiction
    [BookID] => 1
    [BookName] => Karmen
)
(
    [GroupID] => 1
    [GroupName] => Fiction
    [BookID] => 2
    [BookName] => Thunder
)
I need to build a function so that in the result of it I get a list like the following:
1Fiction
------1 Karmen
------2 Thunder
2Adventure
------3 Forest and so on...
Can anyone help me with a piece of code how to achieve this result?
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Re: multilevel ul with PHP

Post by JNettles »

Foreach control structure. Understand and learn how to use foreach early - it will save you many many headaches later.

For your problem, use foreach to loop through each index in your array and then build your structured array or object - I'd really suggest building a class here to hold this data and it generate it as an array of objects; that'll make it easier later to specify methods for operating on your structure.
Post Reply