I worked on a function for a while to create a multidimensional array of unlimited relationships between parents and children from a single db request. I am very close to completing this, but I still have a few problems.
I will copy my code below and comment on it to show the problems. I hope someone here helps me if possible.
My array created from a db request contains data similar to this:
Array
(
[0] => stdClass Object
(
[role_id] => 1
[role_name] => tester
[parent_id] => 0
)
)
Then I pass this array to the function below to create a tree.
function create_role_tree($data) {
$roles = array();
foreach ($data as $tkey => $tval) {
$role = array();
$role['role_id'] = $data[$tkey]->role_id;
$role['role_name'] = $data[$tkey]->role_name;
$children = build_child($data, $data[$tkey]->role_id);
if( !empty($children) ) {
$role['children'] = $children;
}
$roles[] = $role;
}
return $roles;
}
I added another function, shown below, because I was having problems that created an infinite loop. But in the end, I would like to get this array from one function, if possible.
function build_child($data, $parent) {
$roles = array();
foreach($data as $tkey => $tval) {
if($data[$tkey]->parent_id==$parent) {
$role = array();
$role['role_id'] = $data[$tkey]->role_id;
$role['role_name'] = $data[$tkey]->role_name;
$children = build_child($data, $data[$tkey]->role_id);
if( !empty($children) ) {
$role['children'] = $children;
}
$roles[] = $role;
return $roles;
}
}
}
, . , , , , , , , . - ?
Array
(
[0] => Array
(
[role_id] => 1
[role_name] => tester
[children] => Array
(
[0] => Array
(
[role_id] => 4
[role_name] => test 2
)
)
)
[1] => Array
(
[role_id] => 4
[role_name] => test 2
)
[2] => Array
(
[role_id] => 5
[role_name] => test 3
)
[3] => Array
(
[role_id] => 6
[role_name] => uyuiy
)
[4] => Array
(
[role_id] => 7
[role_name] => uyuiy
[children] => Array
(
[0] => Array
(
[role_id] => 10
[role_name] => bamm
[children] => Array
(
[0] => Array
(
[role_id] => 11
[role_name] => testing tree
)
)
)
)
)
[5] => Array
(
[role_id] => 8
[role_name] => uyuiy
)
[6] => Array
(
[role_id] => 9
[role_name] => test new
)
[7] => Array
(
[role_id] => 10
[role_name] => bamm
[children] => Array
(
[0] => Array
(
[role_id] => 11
[role_name] => testing tree
)
)
)
[8] => Array
(
[role_id] => 11
[role_name] => testing tree
)
)
,