Convert an array of strings, each string has dot separated values, to a multidimensional array in php
✔ Recommended Answer
This code uses a function from this answer to do what you're looking for.
<?php$test = Array( 0 => 'INBOX.Trash', 1 => 'INBOX.Sent', 2 => 'INBOX.Drafts', 3 => 'INBOX.Test.sub folder', 4 => 'INBOX.Test.sub folder.test 2',);$output = array();foreach($test as $element){ assignArrayByPath($output, $element); }debug($output);function assignArrayByPath(&$arr, $path) { $keys = explode('.', $path); while ($key = array_shift($keys)) { $arr = &$arr[$key]; }}function debug($arr){ echo "<pre>"; print_r($arr); echo "</pre>";}
Source: stackoverflow.com
Answered By: Ankit
To convert an array of dot-separated strings to a multidimensional array in PHP, you can use the following code:
phpfunction dotToMultiArray($array) {
$result = array();
foreach ($array as $key => $value) {
$keys = explode('.', $key);
$ref = &$result;
while (count($keys) > 1) {
$currentKey = array_shift($keys);
if (!isset($ref[$currentKey])) {
$ref[$currentKey] = array();
}
$ref = &$ref[$currentKey];
}
$ref[array_shift($keys)] = $value;
}
return $result;
}
This function takes an associative array with dot-separated keys and converts it into a multidimensional array. The keys of the input array represent the dot-separated values, and the values represent the corresponding values of the multidimensional array.
Here's an example usage:
php$input = array(
'first.second.third' => 'value1',
'first.fourth' => 'value2',
'fifth' => 'value3'
);
$output = dotToMultiArray($input);
print_r($output);
The output will be:
csharpArray
(
[first] => Array
(
[second] => Array
(
[third] => value1
)
[fourth] => value2
)
[fifth] => value3
)
This function uses a reference to the current level of the multidimensional array in order to create the nested arrays. It also uses array_shift
to remove the first key of the dot-separated string and isset
to check if the nested array exists.
Comments
Post a Comment