将目录中的文件列出到导航中 - 需要首先添加类
我一直在使用以下内容从特定目录输出导航,但需要稍微调整它。如何将 class="first"
添加到输出的第一个
项?对于我的一生,我似乎无法弄清楚如何!<?php
function navigation($path) {
if ($handle = opendir($_SERVER["DOCUMENT_ROOT"].$path)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && $file != 'index.php') {
$label = str_replace('.php', '', $file);
$label = str_replace("-", " ", $label);
$label = ucfirst($label);
$file = str_replace('.php', '/', $file);
$links[] = '<li><a href="' . $path . $file . '" title="' . $label . '">' . $label . '</a></li>' . "\n";
sort($links);
}
}
foreach($links as $link) {
echo ($link);
}
closedir($handle);
}
}
?>
然后我调用 我希望它出现在页面中的位置。
目前会输出如下内容:
<ul>
<li><a href="Path to file" title="Label">Label</a></li>
<li><a href="Path to file" title="Label">Label</a></li>
</ul>
I've been using the following to output navigation from a specific directory but need to adjust it slightly. How can I add class="first"
to the first <li>
item that is outputted? For the life of me I can't seem to work out how!
<?php
function navigation($path) {
if ($handle = opendir($_SERVER["DOCUMENT_ROOT"].$path)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && $file != 'index.php') {
$label = str_replace('.php', '', $file);
$label = str_replace("-", " ", $label);
$label = ucfirst($label);
$file = str_replace('.php', '/', $file);
$links[] = '<li><a href="' . $path . $file . '" title="' . $label . '">' . $label . '</a></li>' . "\n";
sort($links);
}
}
foreach($links as $link) {
echo ($link);
}
closedir($handle);
}
}
?>
I then call <?php navigation("/directory-name/"); ?>
where I want it to appear in the page.
This currently would output something like:
<ul>
<li><a href="Path to file" title="Label">Label</a></li>
<li><a href="Path to file" title="Label">Label</a></li>
</ul>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定我完全理解,但我可以给你我的猜测。
首先,在 while 循环外部启动此变量。
然后,在 while 循环的最后,执行以下操作:
在将其设置为 false 之前,只需使用它来查找该项目是否是第一个:
并将
li
标记内的$class
变量输出字符串。I'm not sure I completely understand, but I can give you what I guessed.
First, initiate this variable outside of the while loop.
Then, at the very end of the while loop, do this:
Before you set that to false, just use this for finding if the item is the first:
And put the
$class
variable inside theli
tag the output string.使用变量
第一次重复循环时,变量
$first_time
等于true。然后,您可以在 if 语句中使用该变量来确定当前 li 元素的类。将您的代码编辑为此
Using a variable
The first time the loop will be repeated the variable
$first_time
equals to true. You can then use that variable in an if statement to determine the class of the currentli
element.Edit your code to this
我会将
标记从第一轮链接创建中取出,以便创建链接的行只是
然后将它们添加到最终迭代中(因为这是在您排序之后) )
I would take the
<li>
tags out of the first round of link creation, so that the line that creates the link would just beAnd then add them in the final iteration (since that's after your sort)