doudou20145 2019-07-03 18:26
浏览 69
已采纳

如何使用值将单个数组转换为多维数组?

Say I have an array:

$my_arr = ['folder1/', 'file2.png', 'file3.png', 'file4.png', 'file5.png', 'folder2/', 'file1.png', 'file6.png'];

And I want to make a multidimensional array categorized by the folders. Since it's not an associative array, I'm having trouble finding a way to split it on the folder values and having the files input into the same array.

Sorry if this doesn't make sense, I'm new to PHP and not finding anything on it thus far.

  • 写回答

1条回答 默认 最新

  • duanmu2941 2019-07-03 18:43
    关注

    If I am not mistaken, one option for your example data could be to use a foreach and check if the string ends on a /

    If is does, add it as a folder with an empty array and mark the current directory. If it is not, add it to the current directory by using the foldername as the key.

    $my_arr = ['folder1/', 'file2.png', 'file3.png', 'file4.png', 'file5.png', 'folder2/', 'file1.png', 'file6.png'];
    $result = [];    
    $folder = '';
    
    foreach ($my_arr as $item) {
        if (substr($item, -1) === '/') {
            $folder = $item;
            $result[$folder] = [];
            continue;
        }
        $folder === '' ? $result[] = $item : $result[$folder][] = $item;
    }
    
    print_r($result);
    

    Result

    Array
    (
        [folder1/] => Array
            (
                [0] => file2.png
                [1] => file3.png
                [2] => file4.png
                [3] => file5.png
            )
    
        [folder2/] => Array
            (
                [0] => file1.png
                [1] => file6.png
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。
  • ¥20 如何在visual studio 2022中添加ImageMagick库