This is a dummy of my table
now if i want to find the number of total child nodes of any parent node in each level for ex...
how can I implement this using php? My code is code
Based on what I am understanding, you should transform the table into informative PHP array, something like:
$a = array(
1 => array(
'children' => array(
array(2, 'left'),
array(3, 'right'),
),
'level' => 0
),
2 => array(
'children' => array(
array(4, 'left'),
array(5, 'right'),
),
'level' => 1
),
...
12 => array(
'children' => array(),
'level' => 3
),
);
This task is quite easy, just fetch the table then foreach and assign each row into associated array. Here is the function to get all children count:
function getChildrenCount($nodeId, $a, $rootLevel)
{
$leftChildren = array();
$rightChildren = array();
$countCurrentNode = 0;
$level = $a[$nodeId]['level'] - $rootLevel;
if (empty($a[$nodeId]['children'])) {
return array($level => 1);
} else {
foreach ($a[$nodeId]['children'] as $children) {
if ($children[1] == 'left') {
$leftChildren = getChildrenCount($children[0], $a, $rootLevel);
$countCurrentNode++;
}
if ($children[1] == 'right') {
$rightChildren = getChildrenCount($children[0], $a, $rootLevel);
$countCurrentNode++;
}
}
$current = $leftChildren;
foreach ($rightChildren as $rightLevel => $count) {
if (isset($current[$rightLevel])) {
$current[$rightLevel] += $count;
} else {
$current[$rightLevel] = $count;
}
}
$current[$level] = $countCurrentNode;
return $current;
}
}
The idea is the recursive traversal each node, then calculate number of children based on its level (compared with root level)
How to call:
getChildrenCount(2, $a, $a[2]['level'])
It will return array(level => count):
array (size=3)
0 => int 2 // level 1
1 => int 3 // level 2
2 => int 3 // Should be removed
Then you should remove the last element - it's useless as it's used to count child by level.
Note:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.