Re: Converting string representation of a directory to multi-dimensional array

From: Date: Mon, 05 Feb 2007 18:47:22 +0000
Subject: Re: Converting string representation of a directory to multi-dimensional array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-248369@lists.php.net to get a copy of this message
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: based on an answer to an old post ... below shows how to uses references to walk 'into' an array and set/create multilevel elements - given a bit of thought you should be able to figure out how to apply the concept to your own problem: <?php $ref = null; $keys = array("six","five","four","three","two","one"); $val = "string value"; // the node value $arr = array(); // generated array $ref =& $arr; while ($key = array_pop($keys)) { $ref[$key] = array(); $ref =& $ref[$key]; } $ref = $val; var_dump($arr);

« previous php.general (#248369) next »