我在我的网站上使用以下代码来处理面包屑, 这段代码的问题是我一直得到相同的层次结构而不是真正的层次结构..
例如:url是hxxp://fakesite.com/A/B/C/d
它会打印出来:
首页»A»B»C»D(很好,但请查看下面的链接)
但链接在主页下总是一个级别:
hxxp://fakesite.com/-->Home
hxxp://fakesite.com/A-->A
hxxp://fakesite.com/B-->B
hxxp://fakesite.com/C-->C
而不是
hxxp://fakesite.com/-->Home
hxxp://fakesite.com/A-->A
hxxp://fakesite.com/A/B-->B
hxxp://fakesite.com/A/B/C-->C
如何修复它以获得正确的层次结构
感谢您的帮助!!
<?php
// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ', $home = 'Home') {
// This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
// This will build our "base URL" ... Also accounts for HTTPS :)
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
// Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
$breadcrumbs = Array("<a href=\"$base\">$home</a>");
$last = end(array_keys($path));
// Find out the index for the last value in our path array
$last = end(array_keys($path));
// Build the rest of the breadcrumbs
foreach ($path AS $x => $crumb) {
// Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
$title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));
// If we are not on the last index, then display an <a> tag
if ($x != $last)
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
// Otherwise, just display the title (minus)
else
$breadcrumbs[] = $title;
}
// Build our temporary array (pieces of bread) into one big string :)
return implode($separator, $breadcrumbs);
}
?>
<p><?= breadcrumbs() ?></p>
感谢您的帮助!!
答案 0 :(得分:2)
正如评论中已经提到的,问题是在foreach
循环中,您始终只使用当前 $crumb
。但是,您需要知道到目前为止的所有碎屑。
最简单的方法是引入一个名为$upToNowCrumbs
的新数组。
我已编辑您的代码以包含此数组。然后,您不会仅从当前的crumb构建您的URL,而是从包含所有碎屑的新数组到现在(请注意使用{{创建href
- a
部分implode
部分的新方法1}})。
这是你的新foreach循环:
$upToNowCrumbs = array();
// Build the rest of the breadcrumbs
foreach ($path as $x => $crumb) {
$upToNowCrumbs[] = $crumb;
// Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
$title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));
// If we are not on the last index, then display an <a> tag
if ($x != $last)
$breadcrumbs[] = "<a href=\"$base".implode('/', $upToNowCrumbs)."\">$title</a>";
// Otherwise, just display the title (minus)
else
$breadcrumbs[] = $title;
}