【发布时间】:2020-05-08 03:33:53
【问题描述】:
TL;DR 我正在寻找一个函数来从 PHP 中的一维数组创建嵌套的 <ol> 列表。
1) 目前我的测试页面中有这个简化的标记:
<h2>Spiders</h2>
<h2>Beetles</h2>
<h3>External morphology</h3>
<h4>Head</h4>
<h4>Thorax</h4>
<h4>Legs</h4>
<h3>Anatomy and physiology</h3>
<h2>Ants</h2>
2) 然后通过一个非常简单的函数将其捕获到一个一维数组中,如下所示:
array
(
0 => "H2 Spiders",
1 => "H2 Beetles",
2 => "H3 External morphology",
3 => "H4 Head",
4 => "H4 Thorax",
5 => "H4 Legs",
6 => "H3 Anatomy and physiology"
7 => "H2 Ants"
);
3) 这是棘手的部分,因为我使用带有这些过于复杂的 if 语句的下一个循环来填充多维数组。
$toc = array ();
//
foreach ($array as $value) {
$value_arr = explode(' ', $value, 2);
$depth = str_replace("H", "", $value_arr[0]);
$content = $value_arr[1];
//
if ($depth == 1) $toc[$title] = null;
elseif ($depth == 2) {
if (empty (end ($toc))) $toc[array_key_last ($toc)] = array ($title => null);
else $toc[array_key_last ($toc)][$title] = null;
} elseif ($depth == 3) {
if (empty (end ($toc[array_key_last ($toc)]))) $toc[array_key_last ($toc)][array_key_last ($toc[array_key_last ($toc)])] = array ($title => null);
else $toc[array_key_last ($toc)][array_key_last ($toc[array_key_last ($toc)])][$title] = '';
}
}
输出:
Array (
[Spiders] =>
[Beetles] => Array
(
[External morphology] => Array
(
[Head] =>
[Thorax] =>
[Legs] =>
)
[Anatomy and physiology] =>
)
[Ants] =>
)
4) 最后用这个函数解析成一个完美缩进的html列表。
function table_of_contents ($toc, $output = '') {
foreach ($toc as $key => $value) {
$output = "$output <li><a href='#@" . sanitize_title ($key) . "'>$key</a>" . (is_array ($value) ? table_of_contents ($value) : null) . '</li>';
}
//
return "<ol>$output</ol>";
}
//
table_of_contents ($toc);
-
- 蜘蛛
- 甲虫
- 外部形态
- 头
- 胸部
- 腿
- 解剖学和生理学
- 外部形态
- 蚂蚁
在第 1、第 2 和第 4 步中一切正常,但我目前的方法有一个缺点,即在第 3 步中只允许我从第一个数组开始最多三个级别的深度。
我的问题是,是否有一种更高效、更简洁的方法来创建具有(可能)递归函数或类似函数的多维数组?
【问题讨论】:
-
@Saf 抱歉,不知何故我错过了那部分,我只是从第一个数组中的标题标签中得到它;例如,
Foo
将变为“H2 Foo”和 $depth = '2' 和 $content = 'Foo'。我已经更正了这个问题。
标签: php html multidimensional-array tableofcontents