将数组值从父级复制到子级

问题描述 投票:-1回答:1

我有一个树结构数组:

array(
    array(
        'id' => 0,
        'tags' => array('q', 'w', 'e', 'r'),
        'children' => array(
            array(
                'id' => 1,
                'tags' => array(),
                'children' => array(
                    array(
                       'id' => 2,
                       'tags' => array(),
                    )
                )
            )
        )
    ),
    array(
        'id' => 0,
        'tags' => array('q', 'w', 'e', 'r'),
        'children' => array(
            array(
               'id' => 3,
               'tags' => array(),
            )
        )
    ),  
);

如果子标签为空,我想将父标签复制给子标签。

array(
    array(
        'id' => 0,
        'tags' => array('q', 'w', 'e', 'r'),
        'children' => array(
            'id' => 1,
            'tags' = >array('q', 'w', 'e', 'r'),
            'children' => array(
                array(
                   'id' => 2,
                   'tags' => array('q', 'w', 'e', 'r'),
                )
            )
        )
    ),
    array(
        'id' => 0,
        'tags' => array('Q', 'B', 'G', 'T'),
        'children' => array(
            array(
                'id' => 3,
                'tags' => array('1', '2', '3', '4'),
                'children' => array(
                    array(
                        'id' => 4,
                        'tags' => array('1', '2', '3', '4'), 
                    )  
                )
            )
        )
    ),  
);

我已经尝试编写一个递归函数来解决此问题,但目前我没有任何想法。

编辑:经过几个小时的工作,我想出了解决方案。

php multidimensional-array tree-traversal
1个回答
0
投票
function inheritTags(&$tree, $parentNode)
{
    foreach ($tree as &$item){
        if (empty($item['tags']))
            $item['tags'] = $parentNode['tags'];

        if (!empty($item['children']))
            inheritTags($item['children'], $item);
    }
}

inheritTags($tree, 0);
© www.soinside.com 2019 - 2024. All rights reserved.