Re: Converting string representation of a directory to multi-dimensional array
| From: | Jochem Maas | Date: | Tue, 06 Feb 2007 11:45:22 +0000 |
| Subject: | Re: Converting string representation of a directory to multi-dimensional array | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-248425@lists.php.net to get a copy of this message | ||
Richard Lynch wrote:
> On Mon, February 5, 2007 12:27 pm, Matt Carlson wrote:
>> Over the weekend, I was tasked with taking a string representation of
>> a directory ('\Interface\Addons\<some dir>\<some file>'), which can
>> vary in length (no set number of depths) to a multi-dimensional array
>> (i.e. array('Interface' => array('Addons' =>
>> array('<some dir>' =>
>> <somefile>)));).
>>
>> We came up with a very ugly hack to do it, but I'm curious if anyone
>> can help us wrap our head around a better solution, without using eval
>> (which we were able to find that solution quickly, but do not want to
>> use eval).
>>
>> Our situation is a little unique in the fact that these files don't
>> actually exist on a filesystem, so it makes it a bit more tough to
>> actually create this array.
>>
>> Thanks for any help you can give in cleaning this up somewhat.
>>
>> Here is the function we currently use:
>>
>> <?php
>>
>> $array = array();
>>
>> addToList('\interface\addons\clearfont\clearfont.toc2', $array);
>> addToList('\interface\addons\clearfont\clearfont.toc3', $array);
>> addToList('\interface\addons\clearfont\clearfont.toc4', $array);
>> addToList('\interface\addons\clearfont\clearfont.toc5', $array);
>> addToList('\interface\addons\clearfont\subdir\something.toc', $array);
>
> function addToList($path){
> $parts = explode('\\', $path);
> $result = array();
> $parts = array_reverse($parts);
> foreach($parts as $part){
> //something with array_splice here...
> $result = array_splice(array($result), $part); //???
array_splice won't cut it as it only splices at 1 level, unless I misunderstood
the OP is looking to dynamically build a multilevel array - which means
either using recursion or 'reference based array digging' (as I like to call it ;-)
there may also be some kind of solution based on
ArrayArrayArrayIteratorIteratorRecursiveArrayIteratorIteratorRecursiveIterator but
personally I don't grok those exotic forms of SPL interface well enough to tell you.
> }
> }
>