嵌套数组到单个数组保持父项

时间:2013-12-26 23:16:37

标签: php arrays associative-array multidimensional-array

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

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

欢迎任何帮助。

实施例

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

2 个答案:

答案 0 :(得分:1)

这里是简单的递归函数:

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 )

答案 1 :(得分:0)

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