How do you create a multi-dimensional array from hierarchically stored SQL data using the adjacency list method?

StackOverflow https://stackoverflow.com/questions/1273972

Question

Hierarchical Data from SQL

Adjacency List Model

In my model I have a series of objects, each stored with their parent id. I am using the Adjacency list model as my hierarchy method.

All examples of Adjacency list simply output there and then. None try to create a multi dimensional array from the result set.

---------------
| id | parent |
---------------
| 1  | NULL   |
| 2  | 1      |
| 3  | 1      |
| 4  | 2      |
| 5  | 2      |
| 6  | 5      |
---------------

Object

I created an array variable in my class called 'children' and want to add a child object each time I find a child from the db query.

Creating an array within each object and storing the subsequent objects in there feels wrong. Can't I create the array of objects separately? Doing it this way may make it hard to traverse the array when I get it into the view.

I feel like I am I approaching this problem the wrong way?

Is there a smarter way to use PHP arrays than this?

Was it helpful?

Solution

The array of children doesn't have to be part of a class; you can always just make an ad-hoc tree where one node is a hash containing an object and its children. I don't know PHP, but it would look something like:

{
    object => $row1,
    children => [
        {
            object => $row2,
            children => [ ... ],
        }, {
            object => $row3,
            children => [],
        }
    ]
}

OTHER TIPS

Do you need it to be an array? An option could be to have the objects implement a recursive hierarchical structure like this one:

http://www.php.net/~helly/php/ext/spl/classRecursiveArrayIterator.html

You can add the objects as child and still travel the structure in an array-like fashion.

The documentation on SPL is sparse but it provides some good traversable structures, interfaces and classes. Some good tutorials exist on the web about it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top