我有一系列的位置。这些位置中的每一个都可以具有子位置。每个子位置也可以有孩子,依此类推:
$locations = array(
array("id" => 1, "parent_id" => 0, "name" => "England"),
array("id" => 2, "parent_id" => 0, "name" => "Scotland"),
array("id" => 3, "parent_id" => 0, "name" => "Ireland"),
array("id" => 4, "parent_id" => 0, "name" => "Wales"),
array("id" => 5, "parent_id" => 1, "name" => "East England"),
array("id" => 6, "parent_id" => 1, "name" => "London"),
array("id" => 7, "parent_id" => 6, "name" => "West London"),
array("id" => 8, "parent_id" => 6, "name" => "East London"),
array("id" => 9, "parent_id" => 1, "name" => "East Midlands"),
array("id" => 10, "parent_id" => 9, "name" => "Derbyshire")
);
我想重新构造这个数组,以便子节点是父节点的数组。像这样(未经测试):
$locations = array("id" => 1, "parent_id" => 0, "name" => "England", "children" => array(
array("id" => 5, "parent_id" => 1, "name" => "East England"),
array("id" => 6, "parent_id" => 1, "name" => "London", "children" => array(
array("id" => 7, "parent_id" => 6, "name" => "West London"),
array("id" => 8, "parent_id" => 6, "name" => "East London")))));
这样我就可以使用缩进来打印出来了:
LOCATIONS
England
- East England
- London
-- West London
-- East London
- East Midlands
-- Derbyshire
Scotland
Ireland
Wales
我已经尝试了几种方法,比如按父ID对它们进行分组,但是我无法解决这个问题的逻辑,并且可能有更好的方法(递归,也许?)。
非常感谢。
答案 0 :(得分:2)
您好或许这会对您有所帮助,我只是编写它以快速将包含parent_id的mysql结果转换为可用的数据层次结构。你的输入数组也应该工作。它只有几行,有两个基本循环。不需要递归。一些评论包括:
<?php
$max = count($inputArray);
$tree = array();
$flat = array();
// Create a flat hierarchy array of all entries by their id
for ($i = 0; $i < $max; $i++) {
$n = $inputArray[$i];
$id = $n['page_id'];
$flat[$id] = $n;
}
// Then check all those entries by reference
foreach ($flat as $key => &$child) {
// Add a children array if not already existing
if (!isset($child['children']))
$child['children'] = array();
$id = $child['page_id'];
$pid = $child['parent_id'];
// If childs parent id is larger then zero
if ($pid > 0) {
// Append it by reference, which means it will reference
// the same object across different carriers
$flat[$pid]['children'][] = &$child;
} else {
// Otherwise it is zero level, which initiates the tree
$tree[$id] = &$child;
}
}
$tree = array_values($tree); // Indices fixed, there we go, use $tree further
?>
请注意'&amp;引用'字符。他们完成所有工作,允许通过指向相同的对象从平面数组构建树。
答案 1 :(得分:0)