1, "parent_id" => -6ren">
gpt4 book ai didi

php - 按父/子 ID 重组数组。递归?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:45:45 26 4
gpt4 key购买 nike

我有一组位置。这些位置中的每一个都可以有子位置。每个子位置也可以有子位置,依此类推:

$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 对它们进行分组,但我就是无法理解其中的逻辑,可能有更好的方法(递归,也许?)。

非常感谢。

最佳答案

您好,也许这会对您有所帮助,我只是编写它来快速将包含 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
?>

所以请注意“& 引用”字符。它们完成所有工作,允许通过指向相同的对象从平面数组构建树。

关于php - 按父/子 ID 重组数组。递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com