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

报告相同问题?