gpt4 book ai didi

php - 我们如何将路径添加到数组中的子项?

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

给定这个数组:

$menu_items = array(
array(
'key' => 'aaa',
'children' => array(
array(
'key' => 'www'
),
array(
'key' => 'xxx'
),
)
),
array(
'key' => 'bbb',
'children' => array(
array(
'key' => 'yyy'
),
array(
'key' => 'zzz'
),
)
),
);

我想像这样向数组中的每个节点添加路径:

$menu_items = array(
array(
'key' => 'aaa',
'path' => 'aaa',
'children' => array(
array(
'key' => 'www',
'path' => 'aaa/www'
),
array(
'key' => 'xxx',
'path' => 'aaa/xxx'
),
)
),
array(
'key' => 'bbb',
'path' => 'bbb',
'children' => array(
array(
'key' => 'yyy',
'path' => 'bbb/yyy',
),
array(
'key' => 'zzz',
'path' => 'bbb/zzz',
),
)
),
);

这个菜单项数组只有 2 层,但它可以有更多层。

我尝试过的:

function add_menu_item_path(&$menu_data, $path = '') {

foreach ($menu_data as &$menu_item) {
$path = $path . '/' . $menu_item['key'];
$menu_item['path'] = $path;
if (!empty($menu_item['children'])) {
add_menu_item_path($menu_item['children'], $path);
}
}
}

这并没有像预期的那样工作,可以在这里查看: http://ideone.com/sHdhss

最佳答案

您只需要一个简单的递归函数。当它在数组中移动时,它将跟踪路径并更新项目。

$menu_items = [
["key"=>"aaa","children"=>[["key"=>"www"], ["key"=>"xxx"]]],
["key"=>"bbb", "children"=>[["key"=>"yyy"], ["key"=>"zzz"]]]
];

function add_path(&$menu, $path = "") {
if (!is_array($menu)) {
return false;
}
foreach ($menu as &$item) {
if (is_array($item) && array_key_exists("key", $item)) {
$item["path"] = trim("$path/$item[key]", "/");
}
if (array_key_exists("children", $item) && is_array($item["children"])) {
add_path($item["children"], "$path/$item[key]");
}
}
}

add_path($menu_items);
print_r($menu_items);

编辑:现在您已经发布了您的代码,我可以看到您非常接近我的想法。你的问题是你每次都附加到路径,所以它变得越来越长: $path = $path 。 '/' 。 $menu_item['key'];

关于php - 我们如何将路径添加到数组中的子项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41604327/

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