Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
634 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...