views:

351

answers:

2

Hierachical 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 hierachy 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 seperately? 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?

Thanks!

+1  A: 

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.

koen
+1  A: 

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 => [],
        }
    ]
}
Eevee
This is the way I chose to take on the problem. It keeps the array nice and tidy as the object is kept inside a node rather than the array being a node of the object. Helpful as my object is quite complex.
Jon Winstanley