一个利用数组来实现无限级分类php类程序,有需要的朋友可参考,这里就不多说什么了直接复制上代码.
php无限级分类(带层深)算法实例代码如下:
- <?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
- ),
- );
-
-
-
-
-
-
-
-
- function createMenuTree($data = array(), $pid = 0)
- {
- if (emptyempty($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;
- }
-
-
-
-
-
-
-
-
- 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";
- }
- ?>
|