程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP不使用遞歸的無限級分類

PHP不使用遞歸的無限級分類

編輯:關於PHP編程

PHP不使用遞歸的無限級分類


不用遞歸實現無限級分類,簡單測試了下性能比遞歸稍好一點點點,但寫得太復雜了,還是遞歸簡單方便點
PHP不使用遞歸的無限級分類

代碼:

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;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved