包含路径作为多维数组的字符串的变量?

2021-12-21 00:00:00 path multidimensional-array php

我正在寻找一个字符串,例如

I'm looking to take a string such as

"/test/uri/to/heaven"

并将其转换为多维嵌套数组,例如:

and turn it into a multi-dimensional, nested array such as:

array(
    'var' => array(
        'www' => array(
            'vhosts' => array()            
        ),
    ),
);

有大佬指点一下吗?我已经浏览过谷歌和这里的搜索,但我什么也没看到.

Anyone got any pointers? I've had a look through Google and the search here, but I've not seen anything.

推荐答案

这是一个快速的非递归黑客:

Here is a quick non recursive hack:

$url   = "/test/uri/to/heaven";
$parts = explode('/',$url);

$arr = array();
while ($bottom = array_pop($parts)) {        
    $arr = array($bottom => $arr);
}

var_dump($arr);

输出:

array(1) {
  ["test"]=>
  array(1) {
    ["uri"]=>
    array(1) {
      ["to"]=>
      array(1) {
        ["heaven"]=>
        array(0) {
        }
      }
    }
  }
}

相关文章