How to Remove Trailing Comma

不打扰是莪最后的温柔 提交于 2019-12-25 16:47:02

问题


I am trying to remove the trailing comma from my php statement

<?php foreach( $speaker_posts as $sp ): ?>
{
    "@type" : "person",
    "name" : "<?php the_field('name_title', $sp->ID); ?>",
    "sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
},
<?php endforeach; ?>

回答1:


Assuming your array is well formed (has indexes starting from zero) you can put it at the beginning, skipping the first record:

<?php foreach( $speaker_posts as $idx => $sp ): ?>
<?php if ($idx) echo ","; ?>
{
    "@type" : "person",
    "name" : "<?php the_field('name_title', $sp->ID); ?>",
    "sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>

Otherwise you need an external counter:

<?php $idx = 0; foreach( $speaker_posts as $sp ): ?>
<?php if ($idx++) echo ","; ?>
{
    "@type" : "person",
    "name" : "<?php the_field('name_title', $sp->ID); ?>",
    "sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>



回答2:


Since you're apparently outputting JSON, use PHP to do it.

<?php

$json = [];

foreach($speaker_posts as $sp) {
    $json[] = [
        '@type' => 'person',
        'name' => get_field('name_title', $sp->ID),
        'sameAs' => post_permalink( $sp->ID ),
    ];
}

print json_encode($json);

?>

Side note: this will save you from potentially unsafe characters like quotation marks / apostrophes in the field/permalink contents.



来源:https://stackoverflow.com/questions/40094450/how-to-remove-trailing-comma

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!