How to convert flattened array to multidimensional array in PHP

I am trying to convert array key values ​​to multidimensional array. Key values ​​appear to be multidimensional, but are just plain text. I tried to hack a string and create a new array, but I feel like there must be something simpler than just this.

See example below:

Array (
[Template[URL]] => http://www.asdasdda.com
[Template[UPC]] => 5484548546314
[Field[value]] =>  Test Example
[Field[answer]] => 20 )

      

All help is very handy. :)

UPDATE: This is the exact output of the data before I ran json_decode on the data.

{"Template[URL]":"http://www.asdasdda.com","Template[UPC]":"5484548546314","Field[value]":"Test Example","Field[answer]":"20"}

      

+3


source to share


2 answers


Hid a little and I think I got it. I don't think there is an easier way:

foreach ($array as $key=>$value) {
    preg_match("/\[(.+)\]/",$key,$match);
    $newKey = preg_replace("/\[.+\]/","",$key);
    $newArray[$newKey][$match[1]] = $value;
}

      



Where a print_r()

of $newArray

looks like this:

Array ( 
    [Template] => Array ( 
        [URL] => http://www.asdasdda.com 
        [UPC] => 5484548546314 
        ) 
    [Field] => Array ( 
        [value] => Test Example 
        [answer] => 20 
        ) 
    )

      

+4


source


Probably the problem should be addressed where the array is created. If you don't have access to this, you can use a support loop regex to convert the array:

$array = [
"Template[URL]" => 'http://www.asdasdda.com',
"Template[UPC]" => '5484548546314',
"Multi[Level][Array]" => 'Hello World'
];

function convert(&$array, $key, $value) {
   preg_match_all("/(?=^)[^]]+(?=\[)|(?<=\[)[^]]+(?=\])/", $key, $keys);
   if ($keys = $keys[0]) {
       // Unset original key
       unset($array[$key]);
       // Dig into each level of keys and reassign the reference
       foreach($keys as $key) {
           if (!isset($array[$key])) $array[$key] = null;
           $array = &$array[$key];
       }
       // Set the final level equal to the original value
       $array = $value;
   }
}

foreach($array as $key=>$value) {
   convert($array, $key, $value);
}

print_r($array);

      

Outputs:



Array
(
    [Template] => Array
        (
            [URL] => http://www.asdasdda.com
            [UPC] => 5484548546314
        )

    [Multi] => Array
        (
            [Level] => Array
                (
                    [Array] => Hello World
                )

        )

)

      

Links are used so you can dig up multiple levels if you need to.

+2


source







All Articles