3

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116

2 Answers2

1

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
  • 13,349
  • 10
  • 46
  • 51
1

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
  • 47,412
  • 11
  • 95
  • 127
  • 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 Aug 14 '09 at 12:30