May
09
2024
一个树数组,使用php递归清除儿子数组为空的元素
作者:
绝缘体.. 发布:
2024-05-09 16:52 分类:
未分类 阅读:
抢沙发
一个树数组,有id,parent_id字段,parent_id字段表示父子关系,使用php写一个函数清除儿子数组为空的元素。
要清除树形数组中儿子数组为空的元素,我们可以使用递归的方法来遍历整个数组,并检查每个元素的子数组是否为空。如果为空,我们就从数组中移除它。以下是一个使用PHP编写的示例函数:
function removeEmptyChildren( & $tree, $childrenName = 'children') {
foreach($tree as $key => & $item) {
if (empty($item[$childrenName])) {
unset($tree[$key]);
} else {
removeEmptyChildren($item[$childrenName]);
}
}
$tree = array_values($tree);
}
微信扫一扫,打赏作者吧~