2

Hello I want to put values of single array into a multidimensional array with each value on a n+1 This is my array $structures

Array
(
    [0] => S
    [1] => S.1
    [2] => S-VLA-S
    [3] => SB
    [4] => SB50
)

What I want for output is this

Array
(
[S] => Array(
    [S.1] => Array (
        [S-VLA-S] => Array (
            [SB] => Array (
                [SB50] => Array(
                    'more_attributes' => true
                )
            )
        )
    )
)
)

This is what I have tried so far

$structures = explode("\\", $row['structuurCode']);

foreach($structures as $index => $structure) {
    $result[$structure][$structure[$index+1]] = $row['structuurCode'];
}

The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array

Thanks in advance.

4
  • 11
    More interestingly: Why would you want to do this? Commented Mar 22, 2016 at 13:24
  • 3
    And perhaps just as interesting, what have you tried? Commented Mar 22, 2016 at 13:25
  • The values of the array is a tree structure. I tried by looping with foreach but no result Commented Mar 22, 2016 at 13:29
  • 4
    @JoachimVanthuyne At least you tried something.. Can you edit your original post and post the code you tried. (the loop you mentioned) Commented Mar 22, 2016 at 13:30

2 Answers 2

6

It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:

$result = array_reduce(array_reverse($structures), function ($result, $key) {
    return [$key => $result];
}, ['more_attributes' => true]);

Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.

Sign up to request clarification or add additional context in comments.

2 Comments

That is way better
Thanks this is what I was looking for!
1

Slightly different approach:

    $var = array('a','an','asd','asdf');
    $var2 = array_reverse($var);
    $result = array('more_attributes' => true);
    $temp = array();
    foreach ($var2 as $val) {
        $temp[$val] = $result;
        $result = $temp;
        $temp = array();
    }

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.