PHP:计数数组项,然后删除'/'获取每个数组项


PHP: Count array items and then remove '../' foreach array item

好吧,有点难以解释,但我想做的是为我的网站创建一个子标题。子标题将基于当前的URL,让我们以sub/test/3rdleveldown/blog/post为例。我需要子标题做的是,为url

的每一层创建一个单独的链接

示例:这将产生:

<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>

谁能帮我把每一层的../弄下来?

应该是这样的:

<?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>
)

我相信这正是你需要的。

我知道了,可能有更好的方法,但这应该可以。

<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>

您可以简单地在$request变量上使用segments方法。

$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
*/