Relational databases represent data as rows and columns inside a table; however, this representation is not suitable for hierarchical data. Certain models are available that allow you to store hierarchical data in these databases. One such method is the Adjacency List model. This article shows you how to manipulate adjacency list implementation of hierarchical (tree) data using PHP.
Hierarchical data consists of elements that have parent-child relationships. It can be visualized as a tree-like structure where each node can have one parent and many children. A node that does not have a parent is called root node while a node that does not have any children is called leaf node. Any connecting node is called branch node.
Adjacency list model is a naive solution used (unknowingly) by majority of programmers. In this implementation, each row stores a reference to its parent. This simplifies most database operations except for SELECTing a subtree (remember that the depth of the subtree is unknown).
Since a tree is a recursively defined data structure, it can be traversed naturally using recursion. The code demonstrated in this article uses (i) one query (ii) array to store all results (iii) index for faster iteration (iv) recursion. It does not use references or multiple queries.