PHP - 创建无限深度数组

PHP - Create unlimited depth array

我必须构建 sitemap.html 生成器,它会创建一个 URL 的树。

例如,如果我有那些​​ URLs:

https://some.url/with/something/good/ and https://some.url/with/something/bad/

它会创建这样的东西:

- https://some.url/
   - https://some.url/with/
      - https://some.url/with/something/
          - https://some.url/with/something/good/
          - https://some.url/with/something/bad/

我的网站上有每个 URL 的数组,现在我正在考虑构建多维数组。

上面的例子会被转换成这样:

$url_structure['https://some.url/']['https://some.url/with/']['https://some.url/with/something/']['https://some.url/with/something/good/'] = 0;

看起来像这样:

Array
(
    [https://some.url/] => Array
        (
            [https://some.url/with/] => Array
                (
                    [https://some.url/with/something/] => Array
                        (
                            [https://some.url/with/something/good/] => 0
                            [https://some.url/with/something/bad/] => 0
                        )
                )
        )
)

您知道如何做得更好吗?这是我目前想到的唯一解决方案。

问题是我找不到创建这样的东西的方法,因为我真的不知道这个数组会变得多深。我只有 URLs 数组(大约 20k URLs)。

sitemap.html 的输出是我在上面所做的列表。

您可以使用引用变量以这种方式完成工作

$list = [
'https://some.url/with/something/good/',
'https://some.url/with/something/bad/',
];

$res = [];
foreach ($list as $x) {
    // remove root. you can add it after loop.
    $x = substr($x, strlen('https://some.url/'));
    $path = preg_split('~/+~', trim($x, '/'));
    // point to the array
    $p = &$res;
    foreach($path as $step) {
        if(! isset($p[$step])) {
            //  add next level if it's absent
            $p[$step] = [];
        }
        // go to next level
        $p = &$p[$step];
    }
}

demo