Generating a javascript array in php with "Foreach" Loop - Stack Overflow

So I'm generating a javascript array of objects in php with a for loop.My code looks somewhat li

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 ma at the end of my javascript array. Is there an elegant way to deal with that ma that separates the javascript objects?

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 ma at the end of my javascript array. Is there an elegant way to deal with that ma that separates the javascript objects?

Share edited May 1, 2012 at 9:44 alain.janinm 20.1k11 gold badges67 silver badges113 bronze badges asked Jun 27, 2011 at 21:51 CamelBluesCamelBlues 3,7745 gold badges32 silver badges39 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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

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);

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 ma 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 ?>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742401649a4437031.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信