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?
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 => [],
}
]
}
0 comments:
Post a Comment