php mysqli buildtree and get count of all children

What I want is to know and count all children recursively for each parent.

  • I have 2 pages: children.php and function.php.
  • In my children.php page I have a table of all parents in the db.
  • in my children.php page I pass each parent to a function to get all
    the children recursively, however the function only return 0.

In children.php I have the following:

$r=mysqli_query($link,"SELECT `id`,`parent_id` FROM locations WHERE parent_id = '0'");
$data = array();
while($row = mysqli_fetch_assoc($r)) 
{
    $data[] = $row;
    $child_id = $row['id'];
    $d = buildtree($data, $child_id);
}
echo count($d);

in function.php I have this code:

function buildtree($src_arr, $parent_id, $tree = array())
{
    foreach($src_arr as $idx => $row)
    {
        if($row['parent_id'] == $parent_id)
        {
            foreach($row as $k => $v)
                $tree[$row['sys_id']][$k] = $v;
            unset($src_arr[$idx]);
            $tree[$row['sys_id']]['children'] = buildtree($src_arr, $row['sys_id']);
        }
    }
    ksort($tree);
    return $tree;
}

So, what I am looking after is to return an array of all children recursively of each parent and echo the count of this array.