将字符串分解为嵌套数组 [英] Explode string into nested array

查看:109
本文介绍了将字符串分解为嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

收件人

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

是否可以通过explode/foreach循环来做到这一点?

Is there a way to do this with explode/foreach loop?

推荐答案

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

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

这篇关于将字符串分解为嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆