
本文将探讨如何使用 PHP 将扁平数组转换为树形数组,其中层级关系由点符号表示,并利用 "type" 属性进行区分。我们将深入研究通过层级关系和类型属性对数组进行索引,并构建树形结构的算法。
核心思想是:
以下是 PHP 代码示例:
<?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"
]
];
$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 $keyed["category_label$parent"]["children"][] =& $item;
}
print_r($result);
?>代码解释:
如果 hierarchy 编号在不同 type 下可能重复(例如,"1.1" 在 category_label 和 item 类型下都存在),则需要将 type 和 hierarchy 组合起来作为索引的键,以区分不同的节点。
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 $keyed["category_label$parent"]["children"][] =& $item;
}为了简化代码和避免潜在的错误,建议确保 hierarchy 编号在所有类型中都是唯一的。如果 hierarchy 编号是唯一的,则可以直接使用 hierarchy 作为索引的键:
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 $keyed[$parent]["children"][] =& $item;
}将扁平数组转换为树形结构是一个常见的编程任务。本文提供了一种基于层级关系和类型属性的解决方案。通过建立索引、查找父节点和构建树形结构,可以有效地将扁平数组转换为易于操作和理解的树形结构。在实际应用中,应根据数据的特点选择合适的索引策略,并尽量保证层级编号的唯一性,以简化代码和提高效率。
以上就是基于点符号和类型属性将扁平数组转换为树形数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号