Convert dot syntax like "this.that.other" to multi-dimensional array in PHP
✔ Recommended Answer
Try this number...
function assignArrayByPath(&$arr, $path, $value, $separator='.') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value;}
It will loop through the keys (delimited with .
by default) to get to the final property, and then do assignment on the value.
If some of the keys aren't present, they're created.
Source: stackoverflow.com
Answered By: alex
You can convert dot syntax like "this.that.other" to a multi-dimensional array in PHP using the following code:
phpfunction convert_dot_syntax_to_array($dot_syntax, $value) {
$keys = explode('.', $dot_syntax);
$array = [$keys[array_key_last($keys)] => $value];
while ($key = array_pop($keys)) {
$array = [$key => $array];
}
return $array;
}
$dot_syntax = 'this.that.other';
$value = 'Hello world';
$array = [];
$keys = explode('.', $dot_syntax);
while ($key = array_shift($keys)) {
$array = &$array[$key];
if (empty($keys)) {
$array = $value;
}
}
var_dump($array); // Output: array(1) { ["this"]=> array(1) { ["that"]=> array(1) { ["other"]=> string(11) "Hello world" } } }
The convert_dot_syntax_to_array
function takes a dot syntax string and a value, and returns a multi-dimensional array where the value is assigned to the key specified by the dot syntax.
The code first splits the dot syntax string into an array of keys using explode
. It then uses a while
loop to traverse the array of keys and build the multi-dimensional array.
Within the loop, it first sets the reference of the current key in the $array
variable using the &
operator, so that changes to $array
within the loop also affect the multi-dimensional array. If the loop has reached the last key, it sets the value to the current key in $array
.
Comments
Post a Comment