<?php
/**
* @param array $list 要转换的结果集
* @param string $pid parent标记字段
* @param string $level level标记字段
*/
function list_to_tree($list, $pk=‘id‘, $pid = ‘pid‘, $child = ‘listArea‘, $root = 0) {
//创建Tree
$tree = array();
if (is_array($list)) {
//创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] = &$list[$key];
}
foreach ($list as $key => $data) {
//判断是否存在parent
$parantId = $data[$pid];
if ($root == $parantId) {
$tree[] = &$list[$key];
} else {
if (isset($refer[$parantId])) {
$parent = &$refer[$parantId];
$parent[$child][] = &$list[$key];
}
}
}
}
return $tree;
}
$arr = array(
array(‘id‘=>1,‘pid‘=>0,‘name‘ => urlencode(‘大连‘), ‘code‘ => ‘dd‘, ‘listArea‘ => array()),
array(‘id‘=>2,‘pid‘=>1,‘name‘ => urlencode(‘香港‘), ‘code‘ => ‘dd‘, ‘listArea‘ => array()),
array(‘id‘=>4,‘pid‘=>3,‘name‘ => ‘m‘, ‘code‘ => ‘dd‘, ‘listArea‘ => array()),
array(‘id‘=>2,‘pid‘=>1,‘name‘ => ‘gg‘, ‘code‘ => ‘aa‘, ‘listArea‘ => array()),
array(‘id‘=>3,‘pid‘=>1,‘name‘ => ‘e‘, ‘code‘ => ‘dd‘, ‘listArea‘ => array())
);
//$array = array(array(‘id‘=>0,‘pid‘=>0,‘name‘ => ‘全国‘));
//$array2 = array_merge($array, $arr);
//array_push($arr, $array);
//print_r($array);exit;
$tree = list_to_tree($arr);
echo json_encode($tree);
注意:不会显示没有子节点的对象
原文地址:https://www.cnblogs.com/wangchanghong/p/9370875.html