Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode string into nested array

Tags:

arrays

php

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?

like image 501
Joe Avatar asked Aug 27 '14 20:08

Joe


1 Answers

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);
like image 87
silkfire Avatar answered Oct 26 '22 11:10

silkfire