Join different arrays in tree form?

Asked

Viewed 54 times

0

I have a situation where I’m not finding a solution.

Suppose we have two arrays as follows:

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

and other 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 this

br
!_com
    !_example1
    |_example2

or if it is also possible to organize them in a format that you can read in json

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

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

  • Can you give more examples ? This example seems to me maybe a little forced ? Each array entry is a tree level ? Can they have different entries ? The order may be different ? The division is always at the end or it can be in the middle ?

  • the idea is that the values repeated in the same position of the arrays become tree nodes. in the example the two arrays have repeated values in the first position, so this would become an array node.

1 answer

0

I was finally able 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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.