• PHP不使用递归的无限级分类


    不用递归实现无限级分类,简单测试了下性能比递归稍好一点点点,但写得太复杂了,还是递归简单方便点
    PHP不使用递归的无限级分类

    代码:

    <?php
    $list = array(
        array('id'=>1, 'pid'=>0, 'deep'=>0, 'name'=>'test1'),
        array('id'=>2, 'pid'=>1, 'deep'=>1, 'name'=>'test2'),
        array('id'=>3, 'pid'=>0, 'deep'=>0, 'name'=>'test3'),
        array('id'=>4, 'pid'=>2, 'deep'=>2, 'name'=>'test4'),
        array('id'=>5, 'pid'=>2, 'deep'=>2, 'name'=>'test5'),
        array('id'=>6, 'pid'=>0, 'deep'=>0, 'name'=>'test6'),
        array('id'=>7, 'pid'=>2, 'deep'=>2, 'name'=>'test7'),
        array('id'=>8, 'pid'=>5, 'deep'=>3, 'name'=>'test8'),
        array('id'=>9, 'pid'=>3, 'deep'=>2, 'name'=>'test9'),
    );
    function resolve($list) {
        $newList = $manages = $deeps = $inDeeps = array();
        foreach ($list as $row) {
            $newList[$row['id']] = $row;
        }
        $list = null;
        foreach ($newList as $row) {
            if (! isset($manages[$row['pid']]) || ! isset($manages[$row['pid']]['children'][$row['id']])) {
                if ($row['pid'] > 0 && ! isset($manages[$row['pid']]['children'])) $manages[$row['pid']] = $newList[$row['pid']];
                $manages[$row['pid']]['children'][$row['id']] = $row;
            }
            if (! isset($inDeeps[$row['deep']]) || ! in_array($row['id'], $inDeeps[$row['deep']])) {
                $inDeeps[$row['deep']][] = array($row['pid'], $row['id']);
            }
        }
        krsort($inDeeps);
        array_shift($inDeeps);
        foreach ($inDeeps as $deep => $ids) {
            foreach ($ids as $m) {
                // 存在子栏目的进行转移
                if (isset($manages[$m[1]])) {
                    $manages[$m[0]]['children'][$m[1]] = $manages[$m[1]];
                    $manages[$m[1]] = null;
                    unset($manages[$m[1]]);
                }
            }
        }
        return $manages[0]['children'];
    }

    递归实现

    function resolve2(& $list, $pid = 0) {
        $manages = array();
        foreach ($list as $row) {
            if ($row['pid'] == $pid) {
                $manages[$row['id']] = $row;
                $children = resolve2($list, $row['id']);
                $children && $manages[$row['id']]['children'] = $children;
            }
        }
        return $manages;
    }
  • 相关阅读:
    298. Binary Tree Longest Consecutive Sequence
    117. Populating Next Right Pointers in Each Node II
    116. Populating Next Right Pointers in Each Node
    163. Missing Ranges
    336. Palindrome Pairs
    727. Minimum Window Subsequence
    211. Add and Search Word
    年底购物狂欢,移动支付安全不容忽视
    成为程序员前需要做的10件事
    全球首推iOS应用防破解技术!
  • 原文地址:https://www.cnblogs.com/zhouzme/p/5758404.html
Copyright © 2020-2023  润新知