我正在尝试将网站地图生成脚本添加到我用于构建本地托管网站的PHP应用程序中,并且我已经有点陷入将目录解析为嵌套树的问题。首先,我不确定递归实现或迭代实现是否会更有用,因为我已经生成了一些可用于构建地图的目录和文件。
Sitemap类的构造函数如下所示:
public function __construct($base_dir = null) {
if($base_dir === null) {
$base_dir = Application::getPublicContentDir();
}
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base_dir), RecursiveIteratorIterator::SELF_FIRST);
foreach($files as $file) {
$name = $file->getFilename();
if($name !== '..' && $name !== '.') {
$path = $file->getPathname();
$ext = '.' . $file->getExtension();
$path = substr($path, strlen($base_dir));
$path = str_ireplace($ext, null, $path);
$is_index = strrpos($path, '/index');
$is_menu = strrpos($path, '/menu');
$is_sitemap = strrpos($path, '/sitemap');
if($is_index === false && $is_menu === false && $is_sitemap === false) {
$this->site_tree[] = $path;
}
}
}
$this->site_tree = array_unique($this->site_tree);
}
基本上,它将遍历给定目录(默认为在Application中设置为公共内容目录的目录),并输出包含目录树中每个节点的路径的数组,删除文件扩展名和重复项。示例输出如下所示:
/home
/miscellaneous
/miscellaneous/texy_test
/music
/music/samples
/about
/sitemap
/railways
/railways/signalling
/railways/signalling/menu
/railways/signalling/victoria
/railways/signalling/victoria/mckenzie_holland_1873_frames
/railways/signalling/victoria/double_wire_frames
/railways/signalling/uk
/railways/signalling/uk/midland_rotary_interlocking_block
/railways/signalling/uk/lms_speed_signalling
/railways/signalling/germany
/railways/signalling/germany/block_interlocking_principles
我想把输出变成类似的东西:
- "Home":[/home]
- "Miscellaneous":[/miscellaneous]
- "Texy test":[/miscellaneous/texy_test]
- "Music":[/music]
- "Samples":[/music/samples]
- "About":[/about]
- "Sitemap":[/sitemap]
- "Railways":[/railways]
- "Signalling":[/railways/signalling]
- "Victoria":[/railways/signalling/victoria]
- "McKenzie & Holland 1873 Patent Frames":[/railways/signalling/victoria/mckenzie_holland_1873_frames]
- "Double-Wire Frames":[/railways/signalling/victoria/double_wire_frames]
- "United Kingdom":[/railways/signalling/uk]
- "Midland Rotary Interlocking Block":[/railways/signalling/uk/midland_rotary_interlocking_block]
- "LMS Speed Signalling":[/railways/signalling/uk/lms_speed_signalling]
- "Germany":[/railways/signalling/germany]
- "Block and Interlocking Principles":/railways/signalling/germany/block_interlocking_principles]
生成每个列表元素的实际文本处理很容易;我已经写过了,我可以重复使用它,因为当它们出现在路径中时(即在面包屑脚本中,“英国”→“英国”),我倾向于更换相同的短语。我坚持的是列表缩进;我能想到的唯一解决方案是用'/'来爆炸每一行并使用数组计数器,但这感觉很笨拙。
我目前想要输出Texy风格的标记,因为我正在使用Texy处理我的各个页面;但是,如果可以像Texy标记一样简单地构建嵌套列表,那么计算复杂度可能会低得多。