0

I am trying to get the total sum count of children data of a particular parent in a genealogy tree populated from a database using the parent.

i have tried some codes but the result is in kind of a binary form.

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);

output: 111111

expected output: 6

The output from var_dump($finalresult); is:

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) { }
  } 
}
Nick
  • 138,499
  • 22
  • 57
  • 95

1 Answers1

1

This function will count all the children in your $finalresult value:

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

Output:

6

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95