Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
2  
What have you tried? –  Niet the Dark Absol Mar 30 '13 at 14:08
2  
Walk the array back to front ;-) –  Havelock Mar 30 '13 at 14:10

2 Answers 2

up vote 2 down vote accepted

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);
share|improve this answer
    
Thanks! The problem was that I didn't know the use of &. –  Wietse de Vries Mar 30 '13 at 14:25
    
@WietsedeVries you are welcome. –  netme Mar 30 '13 at 14:27

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

share|improve this answer
    
Thanks, but Netme was a bit faster. –  Wietse de Vries Mar 30 '13 at 14:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.