0

我正在遍历一个文件夹并以某种方式格式化它的内容。

我必须从这组字符串中形成一个数组:

home--lists--country--create_a_country.jpg

home--lists--country--list_countries.jpg

profile--edit--account.jpg

profile--my_account.jpg

shop--orders--list_orders.jpg

数组需要如下所示:

<?php
array(
  'home' => array(
     'lists' => array(
       'country' => array(
          'create_a_country.jpg',
          'list_countries.jpg'
       )
     )
   ),
  'profile' => array(
     'edit' => array(
       'account.jpg'
     ),
     'my_account.jpg'
   ),
  'shop' => array(
     'orders' => array(
       'list_orders.jpg',
     )
);

问题是,数组的深度可能无限深,具体取决于文件名有多少“--”分隔符。这是我尝试过的(假设每个字符串都来自一个数组:

    $master_array = array();
    foreach($files as $file)
    {
        // Get the extension
        $file_bits      = explode(".", $file);
        $file_ext       = strtolower(array_pop($file_bits));
        $file_name_long = implode(".", $file_bits);

        // Divide the filename by '--'
        $file_name_bits = explode("--", $file_name_long);

        // Set the file name
        $file_name      = array_pop($file_name_bits).".".$file_ext;

        // Grab the depth and the folder name
        foreach($file_name_bits as $depth => $folder)
        {
            // Create sub-arrays as the folder structure goes down with the depth
            // If the sub-array already exists, don't recreate it
            // Place $file_name in the lowest sub-array

            // .. I'm lost
        }            
    }

谁能阐明我如何做到这一点?所有洞察力都表示赞赏。

w001y

4

1 回答 1

2

尝试这个:

$files=array("home--lists--country--create_a_country.jpg","home--lists--country--list_countries.jpg","profile--edit--account.jpg","profile--my_account.jpg","shop--orders--list_orders.jpg");
$master_array=array();
foreach($files as $file)
{
    $file=explode("--",$file);
    $cache=end($file);
    while($level=prev($file))
    {
        $cache=array($level=>$cache);
    }
    $master_array=array_merge_recursive($master_array,$cache);
}
print_r($master_array);

现场演示

于 2013-05-08T05:39:48.583 回答