Hi all! I'm looking to do the following in php:
$string = "a/b/c/d";
CONVERT TO ARRAY
$array['a']['b']['c']['d'];
Not explode the string into an array, but create a multi-level array with the sting. The problem is i don't know how many levels will the sting bring.
Thanks!
Powi
etogre
09-26-2008, 05:49 PM
Is there a specific reason you are trying to do this? Maybe you can explain what you're trying to do with the data and we can provide an alternative solution.
In any case, here's a quick and dirty way, the only way I could, to do it:
<?php
function explode_multi($string, $value = '', &$size)
{
$keys = explode('/', $string);
$eval_string = '$array = ';
$num_keys = 0;
foreach ($keys as $key)
{
$eval_string .= 'array("'.$key.'" =>';
$num_keys++;
}
$eval_string .= "'".$value."'";
for ($i = 0; $i < $num_keys; $i++)
$eval_string .= ')';
$eval_string .= ';';
eval($eval_string);
$size = $num_keys;
return $array;
}
$string = "a/b/c/d";
$size = 0;
$array = explode_multi($string, 'hello world', $size);
/**/
(print_r($array));
echo $array['a']['b']['c']['d']; // hello world
?>
That said I would not reccomend using this function, especially since you state you do not know the size of your array, which leads me to believe the input data can be anything, and since eval is used the effects could be drastic. So again, tell us what you're trying to do with the data so we can offer a better solution than a 20-dimensional array >.<
$a = "a/b/c/d";
$b = split( "[/]", $a );
print_r( $b );
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
???
etogre
09-26-2008, 07:29 PM
No, you see what he's asking is something like this:
Array
(
[a] => Array
(
[b] => Array
(
[c] => Array
(
[d] => ''
)
)
)
)
I'm interested if someone can come up with a better function than mine... perhaps based on some kind of recursive algorithm?
bigfan
09-26-2008, 07:39 PM
If OP is describing the problem right, this will work:function str_to_multi($str)
{
$str = strrev($str);
$ret_arr = array();
while (strlen($str) > 0) {
$arr = array();
$arr[$str[0]] = $ret_arr;
$ret_arr = $arr;
$str = substr($str, 1);
}
return $ret_arr;
}
$string = 'a/b/c/d';
$string = str_replace('/', '', $string);
$multi_arr = str_to_multi($string);
echo '<pre>';
print_r($multi_arr);
echo '</pre>';
I'm also interested in knowing what it's to be used for.
Adam-AEC
09-27-2008, 10:02 PM
I'm also interested in knowing what it's to be used for.
Ditto.
Anyways, my contribution :)
function bracketize($a) {
return "['${a}']";
}
$string = 'a/b/c/d';
$corrected = implode('', array_map("bracketize", explode('/', $string)));
eval("\$array${corrected} = '';");
print_r($array);
Adam-AEC
09-27-2008, 10:08 PM
Shorter.
$string = 'a/b/c/d';
$corrected = preg_replace(array('/(\w+)/i', '/\//'), array("['$1']", ''), $string);
eval("\$array${corrected} = '';");
print_r($array);