This time I will show you how to quickly generate unlimited classifications in PHP (with code). What are the precautions for quickly generating unlimited classifications in PHP? The following is a practical case, let's take a look.
The simplest example:<?php require('PHPTree.class.php'); //原始数据, 从数据库读出 $data = array( array( 'id'=>1, 'name'=>'book', 'parent_id'=>0 ), array( 'id'=>2, 'name'=>'music', 'parent_id'=>0 ), array( 'id'=>3, 'name'=>'book1', 'parent_id'=>1 ), array( 'id'=>4, 'name'=>'book2', 'parent_id'=>3 ) ); $r = PHPTree::makeTree($data); echo json_encode($r); ?>
["id": 1,
"name": "book",
"parent_id": 0,
"expanded": false, //Do not expand child nodes
"children": [
"children": [
"id": 3,
"name": "book1",
"parent_id": 1,
"name": " "id": 4,
"name": "BOOK2",
"Parent_id": 3,
"Leaf": True
}
]
}
] ##},
The generated data is a tree structure and can be used in conjunction with front-end frameworks such as ExtJS. Git contains a demo of ExtJS, which you can refer to.
Demonstration:
If you don’t need to use the front-end framework and just use HTML output, you can use the following method:
$r = PHPTree::makeTreeForHtml($data);
Get a
one-dimensional array, use the level field to identify the level of classification:
array( array( 'id'=>1, 'name'=>'用户管理', 'parent_id'=>0, 'level'=>0 //一级分类 ), array( 'id'=>1, 'name'=>'用户列表', 'parent_id'=>1, 'level'=>1 //二级分类 ) .... );
Output Select the tag:
echo '<h1>PHPTree树形结构</h1>'; echo '<select style="width:300px;">'; foreach($r as $item){ echo '<option>'; //根据所在的层次缩进 echo str_repeat('......',$item['level']); echo $item['name']; echo '</option>'; } echo '</select>';
git contains a demo that outputs HTML, you can refer to it.
关于数据库的设计,只需要保证包含 id 和 parent_id 字段即可,其他字段可以自行添加,不会影响数据生成。parent_id是父级ID,如果是一级分类,就设为 0 。当然,字段也是可以配置的。请继续往下看,我将介绍一些进阶的使用方法。
展开子节点:
PHPTree::makeTree( $data, array( 'expanded' => true ));
输出的数据为:
[
{
id:1,
name:'book1',
expanded:true,//展开子节点
children:[
...
]
}
]
自定义主键和父键:
//数据库读出 $data = array( array( 'order_id'=>1, //主键 'name'=>'book1', 'pid'=>0, //父键 ... ) ); PHPTree::makeTree( $data, array( 'primary_key' => 'order_id', 'parent_key' => 'pid' ));
输出的数据为:
[
{
order_id:1,
name:'book1',
pid:0,
...
}
]
makeTreeForHtml 方法也支持配置主键和父键。
还有其他字段也可以自定义,但下面这些参数仅支持 makeTree 方法:
$r = PHPTree::makeTree($data, array( 'expanded_key' => 'expanded', 'children_key' => 'children', 'leaf_key' => 'leaf' ));
默认,这些字段的配置都是以ExtJS为参考的,如果你使用zTree框架的话,这些字段就需要重新配置了。
zTree 是一款强大的国产树形框架,它还支持 简单JSON格式,是一维数据格式,实际上就不需要用到PHPTree了。当然,PHPTree输出的数据层次感清晰,zTree也是支持的。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to quickly generate unlimited categories in php (with code). For more information, please follow other related articles on the PHP Chinese website!