I'm trying to create an array of JS objects from a PHP array, but I'm struggling to find a way to insert commas in between each object.
Here's what I'm trying to output:
var things = [
{
a: "foo",
b: "bar"
}, // Comma on this line
{
a: "moo",
b: "car"
} // No comma on this line
];
And here is what I have so far:
var things = [
<?php foreach ($things as $thing): ?>
{
a: "<?php echo $thing->getA(); ?>",
b: "<?php echo $thing->getB(); ?>"
}
<?php endforeach; ?>
];
I suppose I could resort to something ugly, like an if
statement that only runs once:
<?php
$i = 1;
if ($i == 1) {
echo '{';
$i++;
} else {
echo ',{';
}
?>
Is there not a cleaner/better way to do this?