构造无限极分类数组 PHP

构造无限极分类数组 PHP_第1张图片

构造无限极分类数组 PHP_第2张图片

<?php
function hjx($list){
echo '<pre>';print_r($list);echo '</pre>';
}
 //创建树形数组
function createTree($array,$parentid=0){
$result = array();
foreach($array as $key => $val){
if($val['parentid'] == $parentid) {
$tmp = $array[$key];unset($array[$key]);
count(createTree($array,$val['id'])) > 0 && $tmp['children'] = createTree($array,$val['id']);
$result[$key] = $tmp;
}
}
return $result;
}


$rows=array (
  11 => 
  array (
    'id' => '11',
    'name' => '菜单列表',
    'parentid' => '9',
  ),
  10 => 
  array (
    'id' => '10',
    'name' => '添加菜单',
    'parentid' => '9',
  ),
  15 => 
  array (
    'id' => '15',
    'name' => '添加菜单AJAX_2',
    'parentid' => '14',
  ),
  16 => 
  array (
    'id' => '16',
    'name' => '添加菜单AJAX_3',
    'parentid' => '14',
  ),
  13 => 
  array (
    'id' => '13',
    'name' => '添加权限',
    'parentid' => '12',
  ),
  9 => 
  array (
    'id' => '9',
    'name' => '菜单管理',
    'parentid' => '0',
  ),
  12 => 
  array (
    'id' => '12',
    'name' => '权限管理',
    'parentid' => '0',
  ),
  14 => 
  array (
    'id' => '14',
    'name' => '添加菜单AJAX',
    'parentid' => '10',
  ),
); 


hjx(createTree($rows));
?>

以下也有一种思路,不过下面的方法中有漏洞,数组的父级必须排在子级的前面才成立!不过也是一种思路!

<?php 

 $rows=array(
11 => array (
'id' => '11',
'name' => '菜单列表',
'parentid' => '9',
),
10 => array (
'id' => '10',
'name' => '添加菜单',
'parentid' => '9',
),
13 => array (
'id' => '13',
'name' => '添加权限',
'parentid' => '12',
),
9 => array (
'id' => '9',
'name' => '菜单管理',
'parentid' => '0',
),
12 => array (
'id' => '12',
'name' => '权限管理',
'parentid' => '0',
),
14 => array (
'id' => '14',
'name' => '菜单AJAX',
'parentid' => '10',
),
15 => array (
'id' => '15',
'name' => '234',
'parentid' => '14',
),
16 => array (
'id' => '16',
'name' => '234',
'parentid' => '15',
),
); 
function hjx($list){
echo '<pre>';print_r($list);echo '</pre>';
}
function tree($data){
    $result =   array();
    $list   =   array();  //定义索引数组,用于记录节点在目标数组的位置,类似指针
    foreach($data as $val){
        if($val['parentid'] == 0){
            $key    =  $val['id'];
            $result[$key]   =   isset($list[$val['id']]) ? array_merge($val,$list[$val['id']]) : $val;
            $list[$val['id']] = & $result[$key];
        }else{
            $key    =  $val['id'];
            $list[$val['parentid']]['children'][$key] = $val;
            $list[$val['id']]   = & $list[$val['parentid']]['children'][$key];
        }
    }
    return $result;
}
hjx($rows);
hjx(tree($rows));

?>

以上方法有漏洞


你可能感兴趣的:(构造无限极分类数组 PHP)