Revenant Revenant - 1 year ago 322
PHP Question

PHP explode string key into multidimensional array with values

I have an array:

$array = [
"main;header;up" => "main_header_up value",
"main;header;bottom" => "main_header_bottom value",
"main;bottom" => "main_bottom value",
"main;footer;right;top" => "main_footer_right_top value"

What I'd like to get is explode the array keys into multidimensional array but keep the values and the result should be equivalent of this array:

$array = [
"main" => [
"header" => [
"up" => "main_header_up value",
"bottom" => "main_header_bottom value"
"bottom" => ["main_bottom value"],
"footer" => [
"right" => [
"top" => "main_footer_right_top value

I guess I should state that the number of
is not predetermined. There could be none or there could be 10 (or more) of them in a key / index.

Is there any elegant way to achieve this?

Answer Source

Here is what I use for things like this:

$result = array();

foreach($array as $path => $value) {
    $temp = &$result;

    foreach(explode(';', $path) as $key) {
        $temp =& $temp[$key];
    $temp = $value;

  • Loop the array and explode() the keys on ;
  • Loop the exploded values and create nested keys from those values
    • Assign the value of the original array element to the last key

My answer to How to write getter/setter to access multi-level array by key names? may help if you need some functions to do this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download