php 无极限分类并在最后面设置相同的空数组

该文章展示了如何使用PHP处理数组,通过`generateTree`函数构建树形结构,然后用`injectArray`函数在特定深度向树节点注入数据。这两个函数都涉及到递归操作,适用于组织和操作层级数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$list 为数组
$list = $this->generateTree($list);
function generateTree($data)
    {
        $items = array();
        foreach ($data as $v) {
            $items[$v['id']] = $v;
        }
        $tree = array();
        foreach ($items as $k => $item) {
            if (isset($items[$item['pid']])) {
                $items[$item['pid']]['son'][] = &$items[$k];
            } else {
                $tree[] = &$items[$k];
            }
        }
        return $tree;
    }
    $testInjectArray = [];
    $res = $this->injectArray($list, $testInjectArray);
    function injectArray(array $target, array $inject, $depth = 0){
        $hasChildrenKey = array_key_exists('son', $target);
        $hasChildren = $hasChildrenKey && !empty($target['son']);
        if($depth % 2 == 0){
            foreach($target as $k => $v)
                if(is_array($v))
                    $target[$k] = $this->injectArray($v, $inject, $depth+1);
        }
        elseif(!$hasChildren){
            if(!$hasChildrenKey)
                $target['son'] = array();
            $target['son'] = array_merge_recursive($target['son'], $inject);
        }
        elseif($hasChildrenKey){
            $target['son'] = $this->injectArray($target['son'], $inject, $depth+1);
        }
        return $target;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值