php - 递归和引用传递

标签 php recursion pass-by-reference

我有一个具有以下结构的类别树:

[6] => Array
    (
        [id] => 6
        [name] => computers
        [productCount] => 0
        [children] => Array
            (
                [91] => Array
                    (
                        [id] => 91
                        [name] => notebook
                        [productCount] => 5
                        [children] => Array
                            (
                            )
                    )

                [86] => Array
                    (
                        [id] => 86
                        [name] => desktop
                        [productCount] => 0
                        [children] => Array
                            (
                            )
                    )
            )
    )

除了子类别之外,每个类别还可能包含产品(就像一个文件夹可能包含子文件夹和文件)。

我正在尝试编写一个递归函数,我想将此数组作为引用并去除 [productCount] = 0 的叶类别和包含此类空节点的所有父类别。换句话说,在处理之后,我只想拥有那些在任何子级别上包含产品的类别。

我已经写了一些代码,现在正在调试它,它不会去除空节点。可能是我没有正确使用引用。如果可能,请帮我修复它。

    function pruneTree( & $node) {
    if ( ! $node['children'] && ! $node['productCount']) {
        unset($node);
    }
    if ( ! empty($node['children'])) {
        foreach ($node['children'] as $key => $child) {
            pruneTree($node['children'][$key]);
        }
    }
    return;
}

最佳答案

您还可以更改函数中的参数以获取节点数组而不是单个节点。这稍微改变了递归,并避免了传递 key 的需要:

function pruneTree(&$nodes) {
    foreach ($nodes as $key => $node) {
        if (!$node['children'] && !$node['productCount']) {
            unset($nodes[$key]);
        } elseif (!empty($node['children'])) {
            pruneTree($nodes[$key]['children']);
            // This line checks if all the children have been pruned away:
            if (empty($nodes[$key]['children'])) {
                unset($nodes[$key]);
            }
        }
    }
}

此外,添加了一个检查以确保如果所有子节点都被修剪,父节点(现在,叶子)也被修剪。

希望这对您有所帮助!


测试数据:

$data = array(
    6 => array(
        'id' => 6,
        'name' => 'computers',
        'productCount' => 0,
        'children' => array(
            91 => array(
                'id' => 91,
                'name' => 'notebook',
                'productCount' => 5,
                'children' => array()
            ),
            86 => array(
                'id' => 86,
                'name' => 'desktop',
                'productCount' => 0,
                'children' => array()
            )
        )
    )
);

召唤:

pruneTree($data);
echo '<pre>';
print_r($data);
echo '</pre>';

关于php - 递归和引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4322650/

相关文章:

Java - 使用递归填充ArrayList

python - 将变量和列表传递给 Python 中的函数

python - dict.get() 方法返回一个指针

php - 提交空搜索字段时如何停止搜索字段返回所有结果?

php - 从数据库中选择最后没有问号的字符串

python - 令人困惑的 [...] Python 中的列表 : What is it?

python - 递归 Excel 文件以从树结构中查找顶级项目

php - 页面被请求两次

php - 如何使用 get_theme_mod 获取图像的替代文本?

c - 在 C 中通过引用传递参数的替代解决方案