【发布时间】:2011-05-18 09:12:03
【问题描述】:
我有一个具有以下结构的类别树:
[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;
}
【问题讨论】:
-
@Ghommey:是的,在 PHP 中,空数组被认为是虚假的。
标签: php recursion pass-by-reference