-1

I have a tree structure array:

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(),
            )
        )
    ),  
);

I want copy parent tags to children if children tags is empty.

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'), 
                    )  
                )
            )
        )
    ),  
);

I've tried to write a recursive function to solve this problem, but for now I don't have any thoughts to do it.

Edit: after a couple of hours of work I came up with the solution.

Mr.Falstaff
  • 15
  • 1
  • 6

1 Answers1

0
function inheritTags(&$tree, $parentNode = array())
{
    foreach ($tree as &$item){
        if (empty($item['tags']))
            $item['tags'] = isset($parentNode['tags']) ? $parentNode['tags'] : array();;

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

inheritTags($tree);
Mr.Falstaff
  • 15
  • 1
  • 6