Explode string into nested array

后端 未结 1 1731
独厮守ぢ
独厮守ぢ 2020-12-18 09:58

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

array(
    \'item1:item2:itemx\',
    \'item1:item2:itemy\',
    \'itemz\'
)
相关标签:
1条回答
  • 2020-12-18 10:03

    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);
    
    0 讨论(0)
提交回复
热议问题