5, "name" => "Item 5", "all_parents" => [ "id" => 4, "n-6ren">
gpt4 book ai didi

php - 使用递归来累积行而不依赖于类属性变量

转载 作者:行者123 更新时间:2023-12-05 04:33:56 25 4
gpt4 key购买 nike

有这个数组:

[
"id" => 5,
"name" => "Item 5",
"all_parents" => [
"id" => 4,
"name" => "Item 4",
"all_parents" => [
"id" => 3,
"name" => "Item 3",
"all_parents" => [
"id" => 2,
"name" => "Item 2",
"all_parents" => [
"id" => 1,
"name" => "Item 1",
"all_parents" => null
]
]
]
]
]

我创建了一个递归 php 函数,将该数组转换为:

[
["id" => 1, "name" => "Item 1"],
["id" => 2, "name" => "Item 2"],
["id" => 3, "name" => "Item 3"],
["id" => 4, "name" => "Item 4"],
["id" => 5, "name" => "Item 5"],
]

代码是这样的:

private array $breadcrumb = [];
private function generateBreadcrumb($structure) : array
{
if($structure) {
$this->breadcrumb[] = array(
"id" => $structure['id'],
"name" => $structure['name'],
);
$this->generateBreadcrumb($structure['all_parents'] ?? []);
}

return array_reverse($this->breadcrumb);
}

如何在不依赖类属性 $breadcrumb 的情况下重新设计此方法?

最佳答案

按照您的初始代码,您可以:

function generateBreadcrumb($structure, &$output = []) : array
{
if ($structure) {
$output[] = array(
"id" => $structure['id'],
"name" => $structure['name'],
);
$this->generateBreadcrumb($structure['all_parents'] ?? [], $output);
}

return array_reverse($output);
}

但是它可以改进,至少避免每次都调用 array_reverse(),但仅限于根调用。

关于php - 使用递归来累积行而不依赖于类属性变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71276131/

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