php递归无限级树形数据,省市区无限树查询案列
2021-10-15 本文已影响0人
可乐_加冰_
摘自:https://gitee.com/mrpzx/tree
数据格式
<?php
return [
["id"=>"1","city"=>"中国", "parent_id"=>"0"],
["id"=>"2","city"=>"北京", "parent_id"=>"1"],
["id"=>"3","city"=>"北京市", "parent_id"=>"2"],
["id"=>"4","city"=>"东城区", "parent_id"=>"3"],
["id"=>"5","city"=>"西城区", "parent_id"=>"3"],
["id"=>"6","city"=>"丰台区", "parent_id"=>"3"],
["id"=>"7","city"=>"海淀区", "parent_id"=>"3"],
["id"=>"8","city"=>"房山区", "parent_id"=>"3"],
["id"=>"9","city"=>"通州区", "parent_id"=>"3"],
["id"=>"10","city"=>"昌平区", "parent_id"=>"3"],
["id"=>"11","city"=>"上海", "parent_id"=>"1"],
["id"=>"12","city"=>"上海市", "parent_id"=>"11"],
["id"=>"13","city"=>"黄浦区", "parent_id"=>"11"],
["id"=>"14","city"=>"长宁区", "parent_id"=>"11"],
["id"=>"15","city"=>"卢湾区", "parent_id"=>"11"],
["id"=>"16","city"=>"徐汇区", "parent_id"=>"11"],
["id"=>"17","city"=>"普陀区", "parent_id"=>"11"],
["id"=>"18","city"=>"闸北区", "parent_id"=>"11"],
["id"=>"19","city"=>"虹口区", "parent_id"=>"11"],
];
工具类
<?php
declare(strict_types=1);
/**
* 自定义省市区无限树
* Class CityTree
* @package app\utils
*/
class CityTree
{
/**
* 主键名称,根据实际来写
* @var string
*/
private static $primary = 'id';
/**
* 父键名称,根据实际来写
* @var string
*/
private static $parentId = 'parent_id';
/**
* 子节点名称
* @var string
*/
private static $child = 'child';
/**
* 修改主键名称、父键名称、子节点名称
* @param string $primary
* @param string $parentId
* @param string $child
*/
public static function setConfig($primary = '', $parentId = '', $child = ''){
if(!empty($primary)) self::$primary = $primary;
if(!empty($parentId)) self::$parentId = $parentId;
if(!empty($child)) self::$child = $child;
}
/**
* 生成Tree
* @param array $data
* @param number $index
* @return array
*/
public static function makeTree(&$data, $index = 0)
{
$childs = self::findChild($data, $index);
if(empty($childs))
{
return $childs;
}
foreach($childs as $k => &$v)
{
if(empty($data)) break;
$child = self::makeTree($data, $v[self::$primary]);
if(!empty($child))
{
$v[self::$child] = $child;
}
}
unset($v);
return $childs;
}
/**
* 查找子类
* @param array $data
* @param number $index
* @return array
*/
public static function findChild(&$data, $index)
{
$childs = [];
foreach ($data as $k => $v){
if($v[self::$parentId] == $index){
$childs[] = $v;
unset($v);
}
}
return $childs;
}
}