嵌套数组到单个数组,保留父级



问题是将树结构更改为简单的数组结构,其中每个孩子都有所属的父级,示例是目录和文件结构,但我正在寻找一个通用解决方案。

如果写作不好,请随时改进。

欢迎任何帮助。

例。

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

结果应该是这样的:

/*
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',
*/

下面是简单的递归函数:

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

用法:

tree2array($array_1, $array2);

输出:

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 )

我使用 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>';

最新更新