Convert flat array of delimited key path strings to a multidimensional array with each path terminating at an empty array
Asked Answered
R

1

5

I would like to convert these strings into a combined nested array:

array(
    'item1:item2:itemx',
    'item1:item2:itemy',
    'itemz'
)

To

array(
    'item1' => array(
        'item2' => array(
            'itemx' => array(),
            'itemy' => array(),
        )
    )
    'itemz' => array()
)

Is there a way to do this with explode/foreach loop?

Rameau answered 27/8, 2014 at 20:8 Comment(4)
Like in this post [#25511051 ?Kunz
I would prefer a solution with PHP, and using arrays not objects.Rameau
are your strings in an array or are really named $string1, 2 etc. ?Harass
@vlzvl There are nested in a larger array, I didn't include that part for simplicity. I'll make a quick edit...Rameau
E
11

This question has been answered countless of times... please use search before posting a new question.

Anyway, here's one solution:

$strings = array(
                 'item1:item2:itemx',
                 'item1:item2:itemy',
                 'itemz'
                );

$nested_array = array();

foreach($strings as $item) {
    $temp = &$nested_array;

    foreach(explode(':', $item) as $key) {
        $temp = &$temp[$key];
    }

    $temp = array();
}

var_dump($nested_array);
Exasperation answered 27/8, 2014 at 20:27 Comment(2)
I did indeed search before posting. Thanks for your answer anyway.Rameau
There are similar questions yes but this one suited my needs exactly, thanks.Hendecasyllable

© 2022 - 2024 — McMap. All rights reserved.