So I'm generating a javascript array of objects in php with a for loop. My code looks somewhat like this:
<script type="text/javascript">
var items = [
<?php foreach($items as $item): ?>
{
"title" : "<?php echo $item->title ?>",
"image" : "<?php echo $item->getImage()?>",
},
<?php endforeach ?>
];
</script>
This code will not work, since I end up with an extra comma at the end of my javascript array. Is there an elegant way to deal with that comma that separates the javascript objects?
You should use json_encode().
<?php
$jsItems = array();
foreach($items as $item) {
$jsItems[] = array(
'title' => $item->title,
'image' => $item->getImage()
);
}
echo 'var items = '.json_encode($jsItems).';';
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With