Marcio Mazzucato
Marcio Mazzucato

Reputation: 9295

Convert unidimensional array values to keys of a multidimensional array

I have an array like:

$indexes = array('a', 'b', 'c');

And a would like to convert it to an multidimensional array like:

$array['a']['b']['c']

The index quantity is dynamic, i can have 2, 3 or more.

I need to do this convertion and then assign a value to this index. Example:

$array['a']['b']['c'] = 'My value';

I tried a logic using array_keys() and array_flip(), but it doesn't work. Any help will be welcome.

Upvotes: 0

Views: 126

Answers (4)

Marcio Mazzucato
Marcio Mazzucato

Reputation: 9295

I got an interesting solution based on an answer posted by @JasonWoof, it is simple and elegant.

$indexes = array('a', 'b', 'c');

$value = 'My value';

while ($indexes) {
    $value = array(array_pop($indexes) => $value);
}

var_dump($value);

Shows:

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      string(8) "My value"
    }
  }
}

Upvotes: 0

Barry
Barry

Reputation: 3723

A recursive approach

function multiDimArray(array $keys, $value) {
    if (count($keys) == 0) {
        return $value;
    } else {
        $key = array_shift($keys);
        return array( $key => multiDimArray($keys, $value));
    }
}

$multiDimArray = multiDimArray(array('a','b','c','d'), "Hello World!");

Upvotes: 0

dognose
dognose

Reputation: 20899

try it with an iteration i'd say:

<?php
$array = array('a', 'b', 'c');
$target = array();
$current = &$target;
foreach ($array as $k){
  $current[$k] = array();
  $current = &$current[$k];
}
$current = "Hello World";

echo "<pre>";
print_r($target);
echo "</pre>";
?>

Output:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Hello World
                )

        )

)

Upvotes: 1

Harutyun Abgaryan
Harutyun Abgaryan

Reputation: 2023

USE THIS

$array = array('a', 'b', 'c');
$arr = array();
$ref = &$arr;
foreach ($array as $key) {
    $ref[$key] = array();
    $ref = &$ref[$key];
}
$ref = $key;
$array = $arr;

Upvotes: 1

Related Questions