0

I have a problem I cannot fix. I have 2 arrays and a string. The first array contains the keys the second one should use. The first one is like this:

Array
(
    [0] => foo
    [1] => bar
    [2] => hello
)

Now I need a PHP code that converts it to the second array:

Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [hello] => MyString
                )
        )
)

The number of items is variable.

Can someone please tell me how to do this?

2
  • 2
    What have you tried? Commented Mar 30, 2013 at 14:08
  • 2
    Walk the array back to front ;-) Commented Mar 30, 2013 at 14:10

2 Answers 2

3

You should use references to solve this problem:

$a = array (0 => 'foo', 1 => 'bar', 2 => 'hello' );

$b = array();
$ptr = &$b;
foreach ($a as $val) {
    $ptr[$val] = Array();
    $ptr = &$ptr[$val];
}
$ptr = 'MyString';
var_dump($b);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The problem was that I didn't know the use of &.
2

All you need is :

$path = array(
        0 => 'foo',
        1 => 'bar',
        2 => 'hello'
);

$data = array();
$t = &$data;
foreach ( $path as $key ) {
    $t = &$t[$key];
}
$t = "MyString";
unset($t);

print_r($data);

See Live Demo

1 Comment

Thanks, but Netme was a bit faster.

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.