我必须构建sitemap.html生成器,该生成器会创建网址树。
例如,如果我有这些网址:
https://some.url/with/something/good/和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
)
)
)
)
您知道如何做得更好吗?到目前为止,这是我唯一想到的解决方案。
问题是我找不到创建这样的东西的方法,因为我真的不知道该数组的深度。我只有一组网址(大约2万个网址)。
sitemap.html的输出是我上面所做的一个列表。
答案 0 :(得分:1)
您可以使用引用变量以这种方式完成工作
$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];
}
}