0

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.

5

4 Answers 4

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I call same thought :-)
1

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
                )

        )

)

1 Comment

:))) That's what I call same thought
0

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!");

Comments

0

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"
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.