1

我想在二叉树中获取父亲的所有下线,每个父亲都有左右臂,每个臂都有左右臂等。 如下图所示。在我的数据库中,我有一个名为 users 的表,每个用户都有一个父亲 ID 和位置,即 L 或 R。

这是我的功能.. 但它仍然没有得到所有的下线。 如下图

4

1 回答 1

1

有两点让我印象深刻:

  1. $i论据和使用$this->downline_id_arr

考虑做:

$children = array();
foreach($data as $row) {
    $child_id = $row->id;
    $children[$child_id] = array(/**/);
    $children = array_merge($children, $this->getAllDownline($child_id);
}
return $childen;

现在您不需要$i变量 or $this->downline_id_arr

  1. 您正在逐个查询每个节点。

考虑改为按级别查询:

function getAllDownlines($fathers) {
    $data = "SELECT * FROM users WHERE father_id IN (/*fathers*/)";
    $new_father_ids = array();
    $children = array();
    foreach ($data as $child) {
        $children[$child->id] = array(/**/); // etc

        $new_father_ids[] = $child->id;
    }
    $children = array_merge($children, $this->getAllDownlines($new_father_ids);
    return $childen;
}

通常,较少的查询会更快,因此您应该会看到更好的性能。

于 2017-06-01T10:20:15.577 回答