tree=array();//第一步,将分类ID作为数组密,并创建儿童单元foreach( t r e e = a r r a y ( ) ; / / 第 一 步 , 将 分 类 I D 作 为 数 组 密 , 并 创 建 儿 童 单 元 f o r e a c h ( categories as category)$tree[$category[′id′]]=$category;$tree[$category[′id′]][′children′]=array();//第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构.foreach( c a t e g o r y ) $ t r e e [ $ c a t e g o r y [ ′ i d ′ ] ] = $ c a t e g o r y ; $ t r e e [ $ c a t e g o r y [ ′ i d ′ ] ] [ ′ c h i l d r e n ′ ] = a r r a y ( ) ; / / 第 二 步 , 利 用 引 用 , 将 每 个 分 类 添 加 到 父 类 c h i l d r e n 数 组 中 , 这 样 一 次 遍 历 即 可 形 成 树 形 结 构 . f o r e a c h ( tree as key=> k e y => item){ if(item ['pid']!= 0){ $ tree [ $ item [ 'pid' ] ] [ 'children' ] [] =&$ tree [ $ key]; //注意:此处必须传引用否则结果不对if($ tree [ $ key] ['children'] == null){unset($ tree)[ $ key] ['children']); //如果孩子为空,则删除该孩子元素(任选)}}} 第三步,删除无用的非根节点数据foreach( item ['pid']!= 0){ $ tree [ $ item [ 'pid' ] ] [ 'children' ] [] =&$ tree [ $ key]; //注意:此处必须传引用否则结果不对if($ tree [ $ key] ['children'] == null){unset($ tree)[ $ key] ['children']); //如果孩子为空,则删除该孩子元素(任选)}}} 第三步,删除无用的非根节点数据foreach( tree as key=> k e y => category){ if(category ['pid']!= 0){unset( category ['pid']!= 0){unset( tree[ $ key]); }}