首页 > 解决方案 > 从 forEach 循环 PHP 中的最后一个元素中删除逗号

问题描述

我正在尝试创建一个动态模式标记,它应该在模式标记中列出我的所有站点导航元素:

我的最终结果应该像这个例子:

    <script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@graph": 
    [
      {
          "@context": "https://schema.org",
          "@type":"SiteNavigationElement",
          "@id":"#table-of-contents",
          "name": "Section 1",
          "url": "https://www.example.com/page#toc-1"
      },
      {
          "@context": "https://schema.org",
          "@type":"SiteNavigationElement",
          "@id":"#table-of-contents",
          "name": "Section 2",
          "url": "https://www.example.com/page#toc-2"
      },
      {
          "@context": "https://schema.org",
          "@type":"SiteNavigationElement",
          "@id":"#table-of-contents",
          "name": "Section 3",
          "url": "https://www.example.com/page#toc-3"
      },
      {
          "@context": "https://schema.org",
          "@type":"SiteNavigationElement",
          "@id":"#pagination",
          "name": "Previous page",
          "url": "https://www.example.com/page1"
      },
      {
          "@context": "https://schema.org",
          "@type":"SiteNavigationElement",
          "@id":"#pagination",
          "name": "Next page",
          "url": "https://www.example.com/page2"
      } // Last item doesn't have a comma
    ]
}
</script>

我创建了一个成功创建架构的代码。

我遇到的唯一问题:如何从我的 forEach 循环的最后一项中删除 , ?

一直在寻找解决方案。可能应该使用计数器或类似的东西?

我的代码:

$string  = '<script type="application/ld+json" id="hejhest">
                {
                    "@context":"https://schema.org",
                    "@graph":
                    [';
foreach ( $primaryNav as $navItem ) {
        $string .= '{';
        $string .= '"@contex":"https://schema.org/",';
        $string .= '"@type": "SiteNavigationElement",';
$string .= '"@id": "#table-of-contents",';
$string .= '"name": "'. $navItem->title. '",';
        $string .= '"url":"' . $navItem->url . '"';
        $string .= '}';
        if (// some if-statement about not being last in forEach loop) {
            $string .= ',';
        }

    }
    $string .= ']
            }
            </script>';
    echo $string;

标签: phpforeachschema

解决方案


推荐阅读