php無限級分類(帶層深)演算法

來源:互聯網
上載者:User
 代碼如下 複製代碼


<?php
$cates = array(
 array(
  'cid'   => 1,
  'cname' => '新聞',
  'pid'   => 0
 ),

 array(
  'cid'   => 2,
  'cname' => '通知',
  'pid'   => 0
 ),

 array(
  'cid'   => 3,
  'cname' => '國內新聞',
  'pid'   => 1
 ),

 array(
  'cid'   => 4,
  'cname' => '國際新聞',
  'pid'   => 1
 ),

 array(
  'cid'   => 5,
  'cname' => '北京新聞',
  'pid'   => 3
 ),

 array(
  'cid'   => 6,
  'cname' => '上海新聞',
  'pid'   => 3
 ),

 array(
  'cid'   => 7,
  'cname' => '緊急通知',
  'pid'   => 2
 ),

 array(
  'cid'   => 8,
  'cname' => '一般通知',
  'pid'   => 2
 ),
);

/**
 * 產生菜單
 *
 * @param array $data 未經處理資料
 * @param integer $pid 當前分類的父id
 * @return array 處理後資料
 */
function createMenuTree($data = array(), $pid = 0)
{
 if (empty($data))
 {
  return array();
 }

 static $level = 0;

 $returnArray = array();

 foreach ($data as $node)
 {
  if ($node['pid'] == $pid)
  {
   $returnArray[] = array(
    'cid'   => $node['cid'],
    'cname' => $node['cname'],
    'level' => $level
   );

   if (hasChild($node['cid'], $data))
   {
    $level++;

    $returnArray = array_merge($returnArray, createMenuTree($data, $node['cid']));

    $level--;
   }
  }
 }

 return $returnArray;
}

/**
 * 檢查是否有子分類
 *
 * @param integer $cid 當前分類的id
 * @param array $data 未經處理資料
 * @return boolean 是否有子分類
 */
function hasChild($cid, $data)
{
 $hasChild = false;

 foreach ($data as $node)
 {
  if ($node['pid'] == $cid)
  {
   $hasChild = true;
   break;
  }
 }

 return $hasChild;
}

header('Content-Type: text/html; charset=utf-8');

$result = createMenuTree($cates);

foreach ($result as $row)
{
 for ($i = 0; $i < $row['level']; $i++)
 {
  echo "t";
 }

 echo $row['cname'] . "n";
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.