推荐:《PHP视频教程》
public function index()
{
$data = [
[
'id'=>1,
'parent_id' => 0,
'name' => '第一个'
],
[
'id'=>2,
'parent_id' => 0,
'name' => '第二个'
],
[
'id'=>3,
'parent_id' => 1,
'name' => '第三个'
],
];
$r = $this->list_to_tree($data);
dump($r);
}
#数组转树结构#
function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parent_id', $child = 'children'){
// 创建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
$parentId = 0;
if (isset($data[$pid])) {
$parentId = $data[$pid];
}
if ((string)$root == $parentId) {
$tree[] = &$list[$key];
} else {
if (isset($refer[$parentId])) {
$parent = &$refer[$parentId];
$parent[$child][] = &$list[$key];
}
}
}
}
return $tree;}#树结构转数组#
function tree_to_list($tree = [], $children = 'children'){
if (empty($tree) || !is_array($tree)) {
return $tree;
}
$arrRes = [];
foreach ($tree as $k => $v) {
$arrTmp = $v;
unset($arrTmp[$children]);
$arrRes[] = $arrTmp;
if (!empty($v[$children])) {
$arrTmp = tree_to_list($v[$children]);
$arrRes = array_merge($arrRes, $arrTmp);
}
}
return $arrRes;}以上就是PHP数组转树结构以及树结构转数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号