
本文介绍了如何使用 PHP 将一个包含层级关系的扁平数组转换为树形结构。该数组的层级关系通过点符号的字符串表示,并使用 "type" 属性区分不同类型的节点。我们将提供两种解决方案,一种处理非唯一层级编码的情况,另一种则适用于层级编码唯一的情况,并提供相应的代码示例和解释。
在处理具有层级关系的数据时,将扁平数组转换为树形结构是一种常见的需求。本文将介绍如何使用 PHP 实现这一转换,特别是在层级关系通过点符号字符串表示,并且需要根据 "type" 属性进行区分的情况下。
假设我们有一个扁平数组,其中每个元素都包含 "hierarchy"(层级关系,使用点符号表示)、"title"(标题)和 "type"(类型)属性。我们的目标是将这个扁平数组转换为一个树形结构,其中父节点包含子节点的 "children" 属性。
例如,我们有以下扁平数组:
立即学习“PHP免费学习笔记(深入)”;
$array = [
[
"hierarchy" => "1",
"title" => "Fruits",
"type" => "category_label"
],
[
"hierarchy" => "1.1",
"title" => "Citruses",
"type" => "category_label"
],
[
"hierarchy" => "1.1.1",
"title" => "Orange",
"type" => "item"
],
[
"hierarchy" => "1.1",
"title" => "Mango",
"type" => "item"
],
[
"hierarchy" => "1.2",
"title" => "Grape",
"type" => "item"
]
];我们期望的结果是:
[
"hierarchy" => "1",
"title" => "Fruits",
"type" => "category_label",
"children" => [
[
"hierarchy" => "1.1",
"title" => "Citruses",
"type" => "category_label",
"children" => [
[
"hierarchy" => "1.1.1",
"title" => "Orange",
"type" => "item"
]
]
],
[
"hierarchy" => "1.1",
"title" => "Mango",
"type" => "item"
],
[
"hierarchy" => "1.2",
"title" => "Grape",
"type" => "item"
]
]
];如果层级编码不是唯一的(例如,"1.1" 可以同时存在于 "category_label" 和 "item" 类型中),我们需要将 "type" 属性也纳入考虑。
function buildTree(array $array): array
{
$keyed = [];
$result = [];
foreach ($array as $item) {
$keyed[$item["type"] . $item["hierarchy"]] = $item;
}
foreach ($keyed as &$item) {
$parent = pathinfo($item["hierarchy"], PATHINFO_FILENAME);
if ($parent == $item["hierarchy"]) {
$result[] =& $item;
} else {
$parentKey = "category_label" . $parent; // 假设父节点总是 category_label 类型
if (isset($keyed[$parentKey])) {
if (!isset($keyed[$parentKey]["children"])) {
$keyed[$parentKey]["children"] = [];
}
$keyed[$parentKey]["children"][] =& $item;
} else {
// 处理找不到父节点的情况,例如根节点定义错误
$result[] =& $item; // 或者抛出异常
}
}
}
return $result;
}
$tree = buildTree($array);
print_r($tree);代码解释:
注意事项:
如果层级编码是唯一的,则可以简化代码,无需考虑 "type" 属性。
function buildTreeUniqueHierarchy(array $array): array
{
$keyed = [];
$result = [];
foreach ($array as $item) {
$keyed[$item["hierarchy"]] = $item;
}
foreach ($keyed as &$item) {
$parent = pathinfo($item["hierarchy"], PATHINFO_FILENAME);
if ($parent == $item["hierarchy"]) {
$result[] =& $item;
} else {
if (isset($keyed[$parent])) {
if (!isset($keyed[$parent]["children"])) {
$keyed[$parent]["children"] = [];
}
$keyed[$parent]["children"][] =& $item;
} else {
// 处理找不到父节点的情况,例如根节点定义错误
$result[] =& $item; // 或者抛出异常
}
}
}
return $result;
}
$tree = buildTreeUniqueHierarchy($array);
print_r($tree);代码解释:
此代码与非唯一层级编码的解决方案类似,但省略了对 "type" 属性的判断,直接使用 "hierarchy" 作为键。
本文介绍了两种将扁平数组转换为树形结构的 PHP 解决方案。第一种方案适用于层级编码非唯一的情况,需要同时考虑 "type" 属性。第二种方案适用于层级编码唯一的情况,可以简化代码。在实际应用中,您可以根据数据的特点选择合适的解决方案。
以上就是PHP:将扁平数组转换为基于点符号和“type”属性的树形数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号