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?

4
  • Like in this post [stackoverflow.com/questions/25510551/… ? Commented Aug 27, 2014 at 20:11
  • 1
    I would prefer a solution with PHP, and using arrays not objects. Commented Aug 27, 2014 at 20:20
  • are your strings in an array or are really named $string1, 2 etc. ? Commented Aug 27, 2014 at 20:23
  • @vlzvl There are nested in a larger array, I didn't include that part for simplicity. I'll make a quick edit... Commented Aug 27, 2014 at 20:26

1 Answer 1

12

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I did indeed search before posting. Thanks for your answer anyway.
There are similar questions yes but this one suited my needs exactly, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.