Introduction to the method of generating unlimited column trees using php

高洛峰
Release: 2023-03-06 18:52:01
Original
1454 people have browsed it

This article describes how to use php to generate an infinite column tree

ColumnArray:
$arr=Array(

Array('cid' => 2,'cname' => 'News','pid' => 0),
Array('cid' => 4,'cname' =>'Sports ','pid' => 0),
Array('cid' => 5,'cname' => 'Entertainment','pid' => 0),
Array('cid ' => 7,'cname' => 'Hot news','pid' =>2),
Array('cid' => 8,'cname' => 'Niche news' ,'pid' => 2),
Array('cid' => 9,'cname' => 'Folk News','pid' => 8),

) ;

<?php
$arr=Array(
    Array(&#39;cid&#39; => 2,'cname' => '新闻','pid' => 0),
    Array('cid' => 4,'cname' =>'体育','pid' => 0),
    Array('cid' => 5,'cname' => '娱乐','pid' => 0),
    Array('cid' => 7,'cname' => '热点新闻','pid' =>2),
    Array('cid' => 8,'cname' => '小众新闻','pid' => 2),
    Array('cid' => 9,'cname' => '民谣新闻','pid' => 8),
);
function formatTree($array, $pid = 0,$level = 1,$field = array('pid'=>'pid','id'=>'id','children'=>'children')){
        $arr = array();
        foreach ($array as &$v) {
            if ($v[$field['pid']] == $pid) {
                $v['level'] = $level;
                $tem = formatTree($array, $v[$field['id']],$v['level']+1,$field);
                //判断是否存在子数组
                $tem && $v[$field['children']] = $tem;
                $arr[] = $v;
            }
        }
        return $arr;
    }
$tree = formatTree( $arr,0,1, $field = array('pid'=>'pid','id'=>'cid','children'=>'children') );
echo '<pre class="brush:php;toolbar:false">';
print_r( $tree);
?>
Copy after login

The above is the detailed content of Introduction to the method of generating unlimited column trees using php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template