将字符串分解为嵌套数组

时间:2014-08-27 20:08:16

标签: php arrays

我想将这些字符串转换为组合的嵌套数组:

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

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

有没有办法用explode / foreach循环来做到这一点?

1 个答案:

答案 0 :(得分:10)

这个问题已经无数次回答了......请在发布新问题之前使用搜索。

无论如何,这是一个解决方案:

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