简体   繁体   English

组合多个多维数组

[英]Combine multiple multi-dimension arrays

I have a set of menu items, like this: 我有一组菜单项,如下所示:

[
    [ "cat" => [ "subcat" => [ "subsubcat1" => $item]]],
    [ "cat" => [ "subcat" => [ "subsubcat2" => $item2]]],
    [ "cat" => [ "subcat2" => [ "subsubcat3" => $item3]]],
    [ "cat" => [ "subcat2" => [ "subsubcat3" => $item4]]],
    [ "cat2" => [ "subcat2" => [ "subsubcat3" => $item5]]],
];

And I wish to combine them like this: 我希望这样合并它们:

[ 
    "cat" =>
    [
        "subcat" => [
            "subsubcat1" => [ $item ],
            "subsubcat2" => [ $item2 ],
        ],
        "subcat2" => [
            "subsubcat3" => [ $item3, $item4 ]
        ]
    ], 
    "cat2" => [
        "subcat2" => [
            "subsubcat3" => [ $item5 ]
        ]
    ]
];

So I can generate an xml structure like this: 因此,我可以生成这样的xml结构:

<menu>
    <category id="cat">
        <category id="subcat2">
            <category id="subsubcat1">
                <menuitem name="{ $item['title'] }" />
            </category>
         </category>
        [...]
   </category>
</menu>

Maybe the 2nd step can be omitted by using DOM but I can't figure this out. 也许可以通过使用DOM省略第二步,但我无法弄清楚。 I tried array_merge_recursive(...$items) but this will also spread the $item. 我尝试了array_merge_recursive(... $ items),但这也会传播$ item。

How can I merge these multidimenision arrays, when the last value is of the last nested array is another type ( a class in this case)? 当最后一个嵌套数组的最后一个值是另一种类型(在这种情况下为类)时,如何合并这些多维数组? The keys can be overwritten (no duplicate subcat2 in this case, unless the parent differs), but the value in the last array ($item, $item2 etc) need to be appended. 键可以被覆盖(在这种情况下,除非父级不同,否则没有重复的subcat2),但是最后一个数组($ item,$ item2等)中的值需要附加。

This is a recursive function that will add items with that structure. 这是一个递归函数,它将添加具有该结构的项目。

function addItem($item, &$category) {
   if (!is_array($item)) {
      $category[] = $item;
   } else {
      $value = reset($item);
      $key = key($item);
      addItem($value, $category[$key]);
   }
}

You can apply it over the outer array like this: 您可以将其应用于外部数组,如下所示:

$menu = [];

foreach ($initial as $item) {
   addItem($item, $menu);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM