根据面包屑级别动态获取页面链接

我正在尝试通过 PHP 创建一个面包屑菜单,到目前为止有以下内容:


<?php


// 1. Get URL

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);

$address = 'http://'.$_SERVER['HTTP_HOST'];


// 2. Strip extras

foreach($crumbs as $crumb){

    $crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');

    echo "<a href=".$address.">"."<span class='crumbMenu'>".$crumb."</span></a>";

}


?>

假设我有以下页面层次结构: Products > Products Level 2 > Products Level 3


上面的代码会吐出:


Products

Products Level 2

Products Level 3

哪个是正确的。但是,链接不是。


阅读完HTTP_HOST 后,我确定我的方法是错误的,但不确定我可以采取哪些其他方法来动态获取每个面包屑项目链接?

我得到的链接:

localhost:8080

我期待的链接:

  • 产品:/products

  • 产品 2 级/products/products-level-2

  • 产品等级 3 :/products/products-level-2/products-level-3


海绵宝宝撒
浏览 120回答 2
2回答

翻翻过去那场雪

您似乎忘记了向$address变量添加路由,因此所有面包屑都指向基本服务器地址。请尝试以下操作:<?php// 1. Get URL$crumbs = explode("/",$_SERVER["REQUEST_URI"]);$address = 'http://'.$_SERVER['HTTP_HOST'];// 2. Strip extras$build = $address.'/products';foreach($crumbs as $crumb){&nbsp; &nbsp; if(in_array($crumb, [$_SERVER['HTTP_HOST'], 'products'])) {&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; $build .= '/'.$crumb;&nbsp; &nbsp; $crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');&nbsp; &nbsp; echo "<a href=".$address.$build.">"."<span class='crumbMenu'>".$crumb."</span></a>";}?>

喵喵时光机

准备好您的回声非常困难,这没有帮助。我创建了一个小函数,它应该可以满足您的要求。随意修改它以满足您的需要。$crumbs = "/x/y/z";$address = "localhost:8080";$crumbs = explode('/', $crumbs);$end = '';$href = '';foreach ($crumbs as $crumb) {&nbsp; &nbsp; $crumb = str_replace('.php', '', $crumb);&nbsp; &nbsp; $end .= $crumb . ' ';&nbsp; &nbsp; $href .= $crumb . '/';}echo("HREF => " . $href);echo("\n");echo("TITLE => " . $end);
打开App,查看更多内容
随时随地看视频慕课网APP