CamelBlues
CamelBlues

Reputation: 3774

Generating a javascript array in php with "Foreach" Loop

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?

Upvotes: 2

Views: 2065

Answers (3)

webbiedave
webbiedave

Reputation: 48887

For the future, in case you run into this type of looping problem again (regardless if it's json related), you can use a boolean to detect if a comma is needed:

<?php $firstTime = true ?>
<?php foreach($items as $item): ?>
    <?php 
    if (!$firstTime):
        echo ', ';
    else:
        $firstTime = false;
    endif;
    ?>
     {
        "title" : "<?php echo $item->title ?>",
        "image" : "<?php echo $item->getImage()?>",
      }
 <?php  endforeach ?>

Upvotes: 0

Marc B
Marc B

Reputation: 360782

ThiefMaster's got it, but to expand on the answer:

$arr = array()
foreach ($items as $item) {
    $arr[] = array('title' => $item->title, 'image' => $item->getImage());
}

echo json_encode($arr);

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318608

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).';';
?>

Upvotes: 10

Related Questions