php - 从 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;
解决方案
推荐阅读
- tensorflow - 使用由 2D 样本制作的张量来馈送 TFX 管道
- .net - 如何以编程方式将自定义名称定义为 firebase 动态链接的短链接(如在控制台中)
- linux - (自动)挂载(usb-)驱动器通过来自python的udisk2 dbus api
- python - 如何将 django 表单绑定到对象实例
- xml - XML Schema - 针对 xml 验证 xsd - 内容无效
- python - 使用自定义路径从源代码在 Linux 上安装 python
- python - Python请求代理'str'对象没有属性'get'
- java - 无法启动组件 [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]] java.util.concurrent.ExecutionException
- python - 多个条件的while循环
- c - 如何在 VS Code 中保存 C 代码的可执行文件