PHP:计算数组项,然后删除'../'foreach数组项

时间:2016-11-06 11:58:15

标签: php laravel

好的,有点难以解释,但我想要做的是为我的网站创建一个子标题。子标题将基于当前URL,以sub/test/3rdleveldown/blog/post为例。我需要副标题做的是,为每个网址级别创建一个单独的链接

示例:这将产生:

<a href="../../../../sub">Sub</a> >> <a href="../../../test">Test</a> >> <a href="../../3rdleveldown">3rdleveldown</a> >> <a href="blog">blog</a>

这将允许用户轻松降低URL级别。

我设法做的就是这个

<div class="subheader">
  <?php
  $uri = $_SERVER['REQUEST_URI'];
  $array = explode('/', $uri);
  $count = count($array);
  ?>
  @foreach ($array as $sub)
    <a href="NOW HERE I NEED TO ENTER the ../ based on how far down the link is in the array {{ $sub }}">{{ $sub }}</a> >>
  @endforeach
</div>

有人可以帮助我降低每个级别的../吗?

3 个答案:

答案 0 :(得分:2)

应该是这样的:

<?php

$path="sub/test/3rdleveldown/blog/post";
$arr = explode("/",$path);
array_pop($arr);
$sarr = sizeof($arr);

$count = 0;
$links = Array();

while ($count < $sarr) {
  $myhref = "<a href=\"";
  /*
   This will add the neccessary number of ../
  */
  for($i=1;$i<=($sarr-$count);$i++) $myhref .= "../";
  $myhref .= $arr[$count] . "\">" . ucfirst($arr[$count]) . "</a>";
  echo $myhref;
  array_push($links, $myhref);
  $count++;
}

print_r($links);

?> 

运行此代码,您将获得

Array
(
    [0] => <a href="../../../../sub">Sub</a>
    [1] => <a href="../../../test">Test</a>
    [2] => <a href="../../3rdleveldown">3rdleveldown</a>
    [3] => <a href="../blog">Blog</a>
)
我相信,这就是你所需要的。

答案 1 :(得分:1)

想出来,可能有更好的方法,但这应该做到。

<div class="subheader">
  <?php
  $uri = $_SERVER['REQUEST_URI'];
  $breadcrums = explode('/', $uri);
  array_pop($breadcrums);
  $count = count($breadcrums);
  --$count;
  $crumlevel = '';
  $ocount = $count;
  ?>
  @foreach ($breadcrums as $breadcrum)
  <?php
    for($count; !$count == 0 ; $count--){
      $crumlevel = '../'.$crumlevel;
    }
    $count = --$ocount;

  ?>
    <a href="{{ $crumlevel.$breadcrum }}">{{ $breadcrum }}</a> >>
    <?php $crumlevel = '../' ?>
  @endforeach
</div>

答案 2 :(得分:-1)

您只需在segments变量上使用$request方法即可。

$segments_arr = request()->segments();
// It would give you an array of URL sub-parts as: 
// ['Sub', 'test', '3rdleveldown'];

然后你可以自己操作那个数组。生成您正在使用的链接的技巧是单向的,或者您可以查看其他Laravel包以创建面包屑。

<强>更新

在迭代段数组时,您可以使用请求request()->root()创建链接。

$root_path = request()->root();
foreach($segments_arr as $segment) {
    $href_str = $root_path . '/' . implode('/', array_slice($segments_arr, 0, $key + 1));
}
/* So for example if your root url is - www.example.com, then
    the output on $key = 0;

    www.example.com/segment1 --- $key = 0
    www.example.com/segment1/segment2 --- $key = 1
*/