参考

时间:2017-05-15 13:46:58

标签: php recursion pass-by-reference

我有参考参数的递归函数。它通过导航,检查是否允许用户查看当前节点。但是当它转到子节点($nodeItem['nodes'])时,它在其实例中运行良好,但不会返回减少的array。这就是问题所在。当它进入我不应该访问的子节点时,它在它的实例中取消它们,但是当它返回数组并且我回到主导航节点数组中时,所有子节点都返回。什么可能是错的?

private function getNodesByRole(&$nodesArray)
{
    foreach ($nodesArray as $nodeKey => $nodeItem) {
        $link = trim($nodeItem['href'], self::SEPARATOR_PRESENTER_LINK);

        if (substr_count($link, self::SEPARATOR_PRESENTER_LINK) == 2) {
            $resource = substr($link, 0, strrpos($link, self::SEPARATOR_PRESENTER_LINK));
            $privilege = substr($link, strrpos($link, self::SEPARATOR_PRESENTER_LINK) + 1);

            if ($this->user->isAllowed($resource, $privilege) === false) {
                unset($nodesArray[$nodeKey]);
                dump($nodeItem);
                dump($nodesArray);
            } else if (!empty($nodeItem['nodes'])) {
                $this->getNodesByRole($nodeItem['nodes']);
            }

        } else {
            if (!empty($nodeItem['nodes'])) {
                $this->getNodesByRole($nodeItem['nodes']);
            }
        }

        if (isset($nodeItem['nodes']) && count($nodeItem['nodes']) == 0) {
            unset($nodesArray[$nodeKey]);
            continue;
        }
    }
    return $nodesArray;
}

1 个答案:

答案 0 :(得分:1)

您需要将返回的数组设置为当前状态数组,如此

private function getNodesByRole(&$nodesArray)
{
foreach ($nodesArray as $nodeKey => $nodeItem) {
    $link = trim($nodeItem['href'], self::SEPARATOR_PRESENTER_LINK);

    if (substr_count($link, self::SEPARATOR_PRESENTER_LINK) == 2) {
        $resource = substr($link, 0, strrpos($link, self::SEPARATOR_PRESENTER_LINK));
        $privilege = substr($link, strrpos($link, self::SEPARATOR_PRESENTER_LINK) + 1);

        if ($this->user->isAllowed($resource, $privilege) === false) {
            unset($nodesArray[$nodeKey]);
            dump($nodeItem);
            dump($nodesArray);
        } else if (!empty($nodeItem['nodes'])) {
            $nodesArray = $this->getNodesByRole($nodeItem['nodes']);
        }

    } else {
        if (!empty($nodeItem['nodes'])) {
            $nodesArray = $this->getNodesByRole($nodeItem['nodes']);
        }
    }

    if (isset($nodeItem['nodes']) && count($nodeItem['nodes']) == 0) {
        unset($nodesArray[$nodeKey]);
        continue;
    }
}
return $nodesArray;
}

希望它有所帮助!