如何从函数内部的foreach循环生成的最后一项中删除最后一个逗号

How to remove the last comma from the last item generated from a foreach loop, inside a function

我看过一些类似的问答,但我还没有成功。有些人建议你用逗号内爆数组,但我不知道在那种特定情况下实施内爆(即使可能)。 我尝试遵循最简单的路径,只删除回显 html 的第 12 个字符(那个该死的逗号),但我无法将函数本身存储到变量中。 如果有任何帮助,我将不胜感激!

<?php
  function jsonbreadcrumbs($home = 'Home') {
  $itemNumber = 1;
  $jsonbreadcrumb .= '<script type="application/ld+json">';
  $jsonbreadcrumb .= '{';
  $jsonbreadcrumb .= '"@context": "http://schema.org",';
  $jsonbreadcrumb .= '"@type": "BreadcrumbList",';
  $root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
  $jsonbreadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
  $jsonbreadcrumb .= '"itemListElement": [{';
  $jsonbreadcrumb .= '"@type": "ListItem",';
  $jsonbreadcrumb .= '"position":' .$itemNumber++.',';
  $jsonbreadcrumb .= "\"name\": \"{$home}\",";
  $jsonbreadcrumb .= "\"item\": \"{$root_domain}\"},";
  foreach ($jsonbreadcrumbs as $crumb) {
    $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
    $root_domain .=  $crumb . '/';
    $jsonbreadcrumb .= '{"@type": "ListItem",';
    $jsonbreadcrumb .= '"position":' . $itemNumber++ . ',';
    $jsonbreadcrumb .= "\"name\": \"{$link}\",";
    $jsonbreadcrumb .= "\"item\": \"{$root_domain}\"},";//<---this last comma,when it belongs to the last item, needs to be removed.
    }
  $jsonbreadcrumb .= ']}</script>';
  return $jsonbreadcrumb;
}
echo jsonbreadcrumbs();
?>

只需trim()它与您自己的角色列表

  foreach ($jsonbreadcrumbs as $crumb) {
    $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
    $root_domain .=  $crumb . '/';
    $jsonbreadcrumb .= '{"@type": "ListItem",';
    $jsonbreadcrumb .= '"position":' . $itemNumber++ . ',';
    $jsonbreadcrumb .= "\"name\": \"{$link}\",";
    $jsonbreadcrumb .= "\"item\": \"{$root_domain}\"},";//<---this last comma,when it belongs to the last item, needs to be removed.
    }
  $jsonbreadcrumb=trim($jsonbreadcrumb,","); // this removes that trailing comma... 
  $jsonbreadcrumb .= ']}</script>';