PHP不使用遞迴的無限級分類簡單一實例_php執行個體

來源:互聯網
上載者:User

不用遞迴實現無限級分類,簡單測試了下效能比遞迴稍好一點點點,但寫得太複雜了,還是遞迴簡單方便點

代碼:

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

以上這篇PHP不使用遞迴的無限級分類簡單一實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.