I have one user which I will consider the root element of my tree structure. Afterwards I have an array of users coming from my database which I consider all the children elements of the tree.
The building of the tree needs to contain the following variables that determine the width and depth of the tree:
Variable: MATCHES_TREE_MAX_DEPTH (eg: 3)
Variable: MATCHES_TREE_ROOT_MAX_CHILDREN_AMOUNT (eg: 2)
Variable: MATCHES_TREE_PARENT_MAX_CHILDREN_AMOUNT (eg: 1)
This means that I want to create a tree structure that is depth 3 (this includes the root element, so I want 2 levels deeper). The root element has 2 children, while any children of children will have have maximum 1 child element.
The order the items are in my users array is the order I want to insert them in the tree (I want to insert them breadth first rather than depth first).
I have found the following generic function on SO: PHP - How to build tree structure list? But I don't seem to be able to adapt it to my use case, since I do not have a parent-child relationship coming from my database.
This SO answer returns me an array that is looking similar, but I'm having issues reforming it to my use case: PHP generate a tree by specified depth and rules
Example data looks like this:
Root user:
object(stdClass)[56]
public 'user_id' => string '1' (length=1)
public 'first_name' => string 'Dennis' (length=6)
Other users (children):
array (size=3)
0 =>
object(stdClass)[57]
public 'user_id' => string '2' (length=2)
public 'first_name' => string 'Tom' (length=3)
public 'street' => string 'Teststreet' (length=10)
1 =>
object(stdClass)[58]
public 'user_id' => string '3' (length=2)
public 'first_name' => string 'Mary' (length=1)
public 'street' => string 'Maryland avenue' (length=15)
2 =>
object(stdClass)[59]
public 'user_id' => string '4' (length=2)
public 'first_name' => string 'Jeff' (length=4)
public 'street' => string 'Teststreet' (length=10)
An example of the tree I want to achieve with the examples filled (taking into account the variables of 3 max depth, 2 children of root and 1 max children of any other element than the root):
Array
(
[userid] => 1
[name] => "Dennis"
[matches] => Array
(
[0] => Array
(
[userid] => 2
[name] => "Tom"
[street] => "Teststreet"
[matches] => Array
(
[0] => Array
(
[userid] => 4
[name] => "Jeff"
[street] => "Teststreet"
[matches] = Array()
)
)
)
[1] => Array
(
[userid] => 3
[name] => "Mary"
[street] => "Maryland avenue"
[matches] => Array
(
)
)
)
)
How do I create this tree structure given the 3 variables that determine the depth and children?