从特定格式的字符串形成数组层次结构

时间:2013-05-08 05:05:10

标签: php arrays multidimensional-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

数组需要如下所示:

<?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

1 个答案:

答案 0 :(得分: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);

Live demo