Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从递归父/子树中获取子节点的总计数_Php - Fatal编程技术网

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

Php 如何从递归父/子树中获取子节点的总计数,php,Php,我试图从使用父项的数据库填充的系谱树中获取特定父项的子项数据的总和 我试过一些代码,但结果是一种二进制形式 function getChildren($parent) { global $connection; $query = "SELECT * FROM member_log WHERE parent_id = $parent"; $result = mysqli_query($connection, $query) or die(mysqli_error($conn

我试图从使用父项的数据库填充的系谱树中获取特定父项的子项数据的总和

我试过一些代码,但结果是一种二进制形式

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) { }
  } 
}

此函数将计算
$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

< P> < /P>显示“<代码>最终结果”的输出,以及你想要的结果(也在你的问题中添加)。你可能想考虑做一个递阶递归查询:问题是updated@Nick我试过了,但似乎没有work@AlivetoDie有什么建议吗