我已经看到了一些类似的问题-答案,但是到目前为止,我还没有做到这一点。有人建议您使用逗号使数组内爆,但我不知道在特定情况下是否实施内爆(即使可能)。 我试图遵循最简单的方法,只是删除了回显的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();
?>
答案 0 :(得分:2)
只需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>';