w001y
w001y

Reputation: 35

Form an array hierarchy from specifically-formatted strings

I'm iterating over a folder and formatting its contents in a certain way.

I've to form an array from this set of strings:

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

The array needs to look like this:

<?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',
     )
);

The thing is, the depth of the array could be infinitely deep depending on how many '--' dividers the file name has. Here's what I've tried (assuming each string is coming from an array:

    $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
        }            
    }

Can anyone shed some light on how I might do this? All insight appreciated.

w001y

Upvotes: 0

Views: 148

Answers (1)

Passerby
Passerby

Reputation: 10080

Try this:

$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

Upvotes: 2

Related Questions