dongzhuo1498 2013-12-26 23:16
浏览 25
已采纳

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

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条回答 默认 最新

  • dougu3988 2013-12-27 01:06
    关注

    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 )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度