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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程