gpt4 book ai didi

php - 递归获取树的所有 child

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:36:33 27 4
gpt4 key购买 nike

我的问题如下:我想获得一个区域的所有子区域。每个区域都有一个定义该区域的代码,以及一个指向其父区域的父区域。

举个例子:

我有代码为 2058 的区域 X。我想要该区域的所有子区域我得到 Y 代码 = 123,parent = 2058,Z 代码 = 500,parent = 2058现在我想要 Y 和 Z 的所有子区域。我将使用代码 [123,500] 并重复该过程,直到区域没有任何子区域。

这是我完成的代码,但出现了一些错误。顺便说一句,我使用的是 PHP 框架,但我希望你能理解代码。

public function findChild($code)
{
$result = array();
$result = $this->db->get_where('zones', array('parent' => $code))->result();
if(empty($result)) {
return array();
} else {
foreach($result as $zone) {
$temp = $this->findChild($zone['code']);
$rr = array_merge($result, $temp);
}
}
return $rr;
}

我哪里做错了,解决这个问题的最佳方法是什么?

我得到的结果只有深度为 1 的 child 。因此,如果代码 = 2058,我只会得到父级 = 2058 的 child 。

最佳答案

问题解决了,只是变量放错了地方。无论如何,如果有人遇到与此类似的问题,解决方案将与我的方法非常相似。

public function findChild($code)
{
$result = $this->db->get_where('zones', array('parent' => $code))->result();
if(empty($result)) {
return array();
} else {
foreach($result as $zone) {
$temp = $this->findChild($zone->code);
$result = array_merge($result, $temp);
}
}
return $result;
}

我使用 $rr 作为数组合并的结果,这实际上是不正确的。我应该合并原始数组。因此,在我之前的代码中,我一直在合并相同的东西。

关于php - 递归获取树的所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56867119/

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