用于获取后代用户列表的树算法

时间:2016-08-24 09:36:47

标签: php algorithm symfony sorting tree

我正在尝试从最多5个级别的用户获取后代用户列表。

该函数应该返回一个包含5个级别的数组,每个数组中都有一个用户列表。

实施例: Example

我已经写了一些内容并且它似乎运行良好但似乎在性能方面这也是一个瓶颈:

注意: getDescendantsForUser 返回一个包含[id,name,parent_id]的User数组,该函数应仅使用$ oUser初始化。

public function getTotalDescendantRecursive(User $oUser, &$level = -1, &$oDescendants = null, &$oPreviousDescendants = null)
{
    if ($level == 6){
        return $oDescendants;
    }

    $oNewDescendants = $this->getDescendantsForUser($oUser);

    if ($oDescendants == null) {
        $oDescendants = array([],[],[],[],[],[]);
        $oDescendants[0] = $oNewDescendants;
    }
    elseif ($oPreviousDescendants != null) {
        // As "array_unique(array_merge..." doesn't work here, we have to check this manually
        $pointerToDescendantsOnLevel = &$oDescendants[$level];
        foreach ($oPreviousDescendants as $key => $value) {
            if (!in_array($value, $pointerToDescendantsOnLevel)) {
                array_push($pointerToDescendantsOnLevel, $value);
            }
        }
        unset($oPreviousDescendants); 
    }

    $level++;

    foreach ($oNewDescendants as $key => $val) {
        $oNewNewDescendants = $this->getTotalDescendantRecursive($val, $level, $oDescendants, $oNewDescendants);
    }

    if ($level != 0) {
        $level--;
    }

    return $oDescendants;
}

你会如何优化它?

提前致谢!

0 个答案:

没有答案