I'm trying to create an array while parsing a string separated with dots
$string = "foo.bar.baz";
$value = 5
to
$arr['foo']['bar']['baz'] = 5;
I parsed the keys with
$keys = explode(".",$string);
How could I do this?
I'm trying to create an array while parsing a string separated with dots
$string = "foo.bar.baz";
$value = 5
to
$arr['foo']['bar']['baz'] = 5;
I parsed the keys with
$keys = explode(".",$string);
How could I do this?
You can do:
$keys = explode(".",$string);
$last = array_pop($keys);
$array = array();
$current = &$array;
foreach($keys as $key) {
$current[$key] = array();
$current = &$current[$key];
}
$current[$last] = $value;
You can easily make a function out if this, passing the string and the value as parameter and returning the array.
You can try following solution:
function arrayByString($path, $value) {
$keys = array_reverse(explode(".",$path));
foreach ( $keys as $key ) {
$value = array($key => $value);
}
return $value;
}
$result = arrayByString("foo.bar.baz", 5);
/*
array(1) {
["foo"]=>
array(1) {
["bar"]=>
array(1) {
["baz"]=>
int(5)
}
}
}
*/
This is somehow related to the question you can find an answer to, here:
PHP One level deeper in array each loop made
You would just have to change the code a little bit:
$a = explode('.', "foo.bar.baz");
$b = array();
$c =& $b;
foreach ($a as $k) {
$c[$k] = array();
$c =& $c[$k];
}
$c = 5;
print_r($b);