duanmoen784988 2018-02-24 23:24
浏览 32

将数组转换为多维数组

I have an array that looks something like this:

array:2 [
    "test1_test2_test3" => "result"
    "category_slug" => "the_slug"
]

What I need to do is convert it to a multidimensional array that would look something like this:

array:2 [
    "test1" => [
        "test2" => [
            "test3" => "result"
        ]
    ]
    "category" => [
        "slug" => "the_slug"
    ]
]

I know that I can explode on the key to get an array but am unsure of how to then go from this to end up with the final result.

EDIT The array looks like that initially because it's being pulled from request parameters: http://url.com?test1.test2.test3=result&category.slug=the_slug and Laravel auto converts it to an array.

  • 写回答

4条回答 默认 最新

  • drj26159 2018-02-24 23:36
    关注

    My approach would be to reverse the array, then loop through the keys and nest them.

    The code below should do the trick.

    $array = [
        "test1_test2_test3" => "result",
        "category_slug" => "the_slug"
    ];
    
    $array = array_map(function ($key, $value) {
        $keys = array_reverse(explode('_', $key));
        while($key = array_shift($keys)) {
            $value = [$key => $value];
        }
    
        return $value;
    }, array_keys($array), $array);
    
    $array = call_user_func_array('array_merge', $array);
    var_dump($array);
    
    /**
    array(2) {
        ["test1"]=>
        array(1) {
            ["test2"]=>
            array(1) {
                ["test3"]=>
                string(6) "result"
            }
        }
        ["category"]=>
        array(1) {
            ["slug"]=>
            string(8) "the_slug"
        }
    }
    */
    
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据