I've setup an "infinite depth" category system which is stored in the database with three important pieces of information:
- Category ID
- Parent Category ID
- NodePath
The first two are self explanatory, but the last one needs some clarification. If the category is #20, it's parent is #10, and the parent's parent is #5, then the NodePath would look like 5:10:20. In this way I can recursively find a categories parent branch.
I'm looking for a way to get every category from the database, and then sort them in some way where the result is an array like this:
array(
0 => array(
3 => array(
7,
13,
),
5,
),
1 => array(
6,
9
),
);
Essentially, this is a map of the tree hierarchy created from the NodePath structure described before.
I've come up with something like this:
$tree = array();
foreach( $categories as $category )
{
// A NodePath Example is "1:7:13:24" where 1 is the root category,
// 24 is the "leaf" or end node, and the other numbers are sub categories
// in order.
$nodes = explode( ":", $category->NodePath );
$lastNode = &$tree;
foreach( $nodes as $node )
{
// Add New Branch if not Termination
if( !isset( $lastNode[ $node ] ) && $node != end($nodes) )
$lastNode[ $node ] = array();
// Recursive Addressing
$lastNode = &$lastNode[ $node ];
}
}
Which produces this var_dump() of the tree (which matches the data in my database):
array (size=3)
1 =>
array (size=1)
4 => null
2 =>
array (size=2)
5 =>
array (size=1)
7 => &null
6 => null
3 => null
The third depth down sets terminal nodes as "&null" instead of just "null". How can I fix this?