Join different arrays in the form of a tree?

0

I have a situation where I can not find a solution.

Suppose we have two arrays as follows:

array('br', 'com', 'example1' )

and another array like this:

array('br','com','example2')

What I would like is to turn these two arrays into just one so that it looks like a data tree like

br
!_com
    !_example1
    |_example2

or if you can also arrange them in a format that you can read in jSon

br:{
   com:{ "example1", "example2" }
}

Could someone propose an algorithm or is there a function in PHP that does this?

    
asked by anonymous 21.05.2018 / 16:00

1 answer

0

I finally managed to work out a solution for this algorithm. Suppose we have the following array:

$itens = array( array('br','com','exemplo1'), array('br,'com','exemplo2'));
$result = array(array());

In my case I created a function that receives the final array by reference as follows:

function treeNodesArray( &$result, $itens)
{
    foreach( $itens as $array ){

       $node = &$result;


       foreach( $array as $value )
       {
        if( $node != null && array_key_exists( $value, $node ))
        {
            $node = &$node[$value];

        }else{
            $node[$value] = array();
            $node = &$node[$value];

        }
      }
    }
}

print_r( $result );

Thank you!

    
21.05.2018 / 18:02