Search code examples
phparraysobjectexplode

Break String in to multilevel object (or array)


I have a string like this: -

dev/clients/518/aaa/1915/bbb/1/file.pdf

and my aim is to be able to refer to file.pdf via a multilevel object

dev->clients->518->aaa->1915->bbb->1

or an array

[dev][clients][518][aaa][1915][bbb][1]

This is a key from AWS S3 from which I am trying to create a navigable structure. I can explode the string to get

Array
(
    [0] => dev
    [1] => clients
    [2] => 518
    [3] => aaa
    [4] => 1915
    [5] => bbb
    [6] => 1
    [7] =>file.pdf
)

Not sure how to move forward from here. This might show what I'm after a little better: -

Array (
    [dev] => Array (
        [clients]  => Array (
            [518] => Array (
                [aaa] => Array (
                    [1915] => Array (
                        [bbb] => Array (
                            [1] => file.pdf
                        )   
                    )
                )   
            )
        )
    )
)

Solution

  • You can do that with simple for-loop:

    $arr = explode("/", "dev/clients/518/aaa/1915/bbb/1/file.pdf");
    $arr = array_reverse($arr); //reverse the order to start from the lowest level
    $res = array_shift($arr); //init the result as the last element ("file")
    foreach($arr as $e) {
        $tmp[$e] = $res;
        $res = $tmp;
        unset($tmp[$e]); //so $tmp will not contain dragging element
    }
    

    You desire output will be in $res