admin管理员组文章数量:1336633
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 badges3 Answers
Reset to default 10You 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 ?>
本文标签: Generating a javascript array in php with quotForeachquot LoopStack Overflow
版权声明:本文标题:Generating a javascript array in php with "Foreach" Loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742401648a2468004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论