如何从递归父/子树中获取子节点的总数

时间:2019-04-23 12:47:49

标签: php

我正在尝试从使用父级的数据库填充的家谱树中获取特定父级的子级数据的总数。

我尝试了一些代码,但结果采用的是二进制形式。

function getChildren($parent) {
    global $connection;
    $query = "SELECT * FROM member_log WHERE parent_id = $parent";
    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $children = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $children[$row['id']]['username'] = $row['username'];
        $children[$row['id']]['children'] = getChildren($row['id']);
    }
    return $children;
}

$user_id = "100";
$finalResult = getChildren($user_id);

$final = count($finalResult);

function printList($array = null) {
    if (count($array)) {
        foreach($array as $item) {
            $e = 1;
            echo $e;

            if (count($item['children'])) {
                printList($item['children']);
                $a = count($item['children']);
            }
        }
    }
}

echo printList($finalResult);

输出:111111

预期输出:6

var_dump($finalresult);的输出是:

array(3) {
  [101]=> array(2) {
    ["username"]=> string(8) "1st user"
    ["children"]=> array(3) {
      [104]=> array(2) {
        ["username"]=> string(8) "4th user"
        ["children"]=> array(0) { }
      }
      [105]=> array(2) {
        ["username"]=> string(8) "5th user"
        ["children"]=> array(0) { }
      }
      [108]=> array(2) {
        ["username"]=> string(7) "new guy"
        ["children"]=> array(0) { }
      }
    }
  }
  [102]=> array(2) {
    ["username"]=> string(8) "2nd user"
    ["children"]=> array(0) { } 
  }
  [103]=> array(2) {
    ["username"]=> string(8) "3rd user"
    ["children"]=> array(0) { }
  } 
}

1 个答案:

答案 0 :(得分:1)

此功能将计算您的$finalresult值中的所有子代:

function count_children($tree) {
    $count = 0;
    foreach ($tree as $child) {
        $count++;
        if (is_array($child['children'])) {
            $count += count_children($child['children']);
        }
    }
    return $count;
}

输出:

6

Demo on 3v4l.org