Converting string representation of a directory to multi-dimensional array
| From: | Matt Carlson | Date: | Mon, 05 Feb 2007 18:27:54 +0000 |
| Subject: | Converting string representation of a directory to multi-dimensional array | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-248366@lists.php.net to get a copy of this message | ||
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($str, &$array)
{
$things = explode('\\', $str);
if($things['0'] == '')
{
array_shift($things);
}
addToArray($things, $array);
}
function addToArray($things, &$array)
{
$count = count($things);
switch ($count)
{
case '1':
$array[$things['0']] = $array();
break;
case '2':
$array[$things['0']][$things['1']] = $things['1'];
break;
case '3':
$array[$things['0']][$things['1']][$things['2']] =
$things['2'];
break;
case '4':
$array[$things['0']][$things['1']][$things['2']][$things['3']]
= $things['3'];
break;
<<previous code repeated down to 10>>
default:
break;
}
}
print_r($array);
?>