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

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

问题描述:

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.

说我有一个数组: p>

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

我想制作一个按文件夹分类的多维数组。 由于它不是关联数组,我很难找到一种方法将其拆分为文件夹值并将文件输入到同一个数组中。 p>

很抱歉,如果这没有意义,我是PHP的新手,到目前为止还没有找到任何内容。 p> div>

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
        )

)