问题
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