0

The problem is to change a tree structure to a simple array structure, in which each child has the parents who belongs to, the example is a directories and files structure, but I'm looking for a generic solution.

If the writing is bad, feel free to improve it.

Any help is welcome.

Example.

$array_1=array(
'f1' => 
    array(
        'f2' =>array('file1.php','file2.php'),
        'f3' =>array('file3.php','file4.php'),
        'f4' =>
            array(
                'fol5'=>
                    array('fileAA.php','fileBB.php')
                ,
                'fileDD.php'
            ),
    ),
'f2' => 
    array(
        'f2' =>array('file1.php','file2.php'),
        'f3' =>array('file3.php'),
    )
);

The result should be like this:

/*
0 => '/f1/f2/file1.php',
1 => '/f1/f2/file2.php',
2 => '/f1/f3/file3.php',
3 => '/f1/f3/file4.php',
4 => '/f1/f4/fol5/fileAA.php',
5 => '/f1/f4/fol5/fileBB.php',
6 => '/f1/f4/fileDD.php',
7 => '/f2/f2/file1.php',
8 => '/f2/f2/file2.php',
9 => '/f2/f3/file3.php',
*/

2 Answers 2

1

here is simple recursive function:

function tree2array($input, &$output, $prefix = '')
{
    foreach ($input as $i => $v)
        if (is_array($v))
            tree2array($v, $output, $prefix.'/'.$i);
        else
            $output[] = $prefix.'/'.$v;
}

usage:

tree2array($array_1, $array2);

output:

print_r($array2);

Array (
    [0] => /f1/f2/file1.php
    [1] => /f1/f2/file2.php
    [2] => /f1/f3/file3.php
    [3] => /f1/f3/file4.php
    [4] => /f1/f4/fol5/fileAA.php
    [5] => /f1/f4/fol5/fileBB.php
    [6] => /f1/f4/fileDD.php
    [7] => /f2/f2/file1.php
    [8] => /f2/f2/file2.php
    [9] => /f2/f3/file3.php )
Sign up to request clarification or add additional context in comments.

Comments

0

I made an alternative solution using SPL

$arrayiter = new RecursiveArrayIterator($array_1);
$iteriter = new RecursiveIteratorIterator($arrayiter,RecursiveIteratorIterator::CHILD_FIRST);

foreach ($iteriter as $key => $value) {

$this_depth = $iteriter->getDepth();

if(!is_array($value)){
        $array_2[] = '/'.$value;
        $level[]=$this_depth;
}

foreach($array_2 as $key2 => $value2){
    if($this_depth < $level[$key2]){
        $level[$key2] = $this_depth;
        $array_2[$key2] = '/'.$key.$value2;
    }
}

}
echo'<pre>';
print_r($array_2);
echo'</pre>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.