Reputation: 878
I tested this on firefox and it works fine, but in IE it doesn't work because of comma on last part of array. Now how can I remove comma using php?
Actual result:
{image : 'folder/pic1.jpg', title : '', thumb : 'folder/pic1.jpg', url : ''},
{image : 'folder/pic2.jpg', title : '', thumb : 'folder/pic2.jpg', url : ''},
{image : 'folder/pic3.jpg', title : '', thumb : 'folder/pic3.jpg', url : ''},
Expected result:
{image : 'folder/pic1.jpg', title : '', thumb : 'folder/pic1.jpg', url : ''},
{image : 'folder/pic2.jpg', title : '', thumb : 'folder/pic2.jpg', url : ''},
{image : 'folder/pic3.jpg', title : '', thumb : 'folder/pic3.jpg', url : ''}
Code:
<?php
$directory = "pic/";
$images = glob("".$directory."{*.jpg,*.JPG,*.PNG,*.png}", GLOB_BRACE);
if ($images != false)
{
?>
<script type="text/javascript">
jQuery(function($){
$.supersized({
slideshow: 1,//Slideshow on/off
autoplay: 1,//Slideshow starts playing automatically
start_slide: 1,//Start slide (0 is random)
stop_loop: 0,
slides: [// Slideshow Images
<?php
foreach( $images as $key => $value){
echo "{image : '$value', title : '', thumb : '$value', url : ''},";
}
?>
],
progress_bar: 1,// Timer for each slide
mouse_scrub: 0
</script>
<?php
}
?>
Upvotes: 0
Views: 237
Reputation: 6687
Upvoted Utkanos' answer to use json_encode
but to get your code to work you can use end
to compare if your values are the same, or key
to verify the keys.
foreach ($array as $key => $value) {
if ($value == end($array)) {
// Last element by value
}
end($array);
if ($key == key($array)) {
// Last element by key
}
}
Upvotes: 1
Reputation: 522042
Don't write your own JSON, use json_encode
:
<?php
$data = array(
'slideshow' => 1,
...
);
foreach ($images ...) {
$data['slides'][] = array('image' => ...);
}
?>
$.supersized(<?php echo json_encode($data); ?>);
Upvotes: 1
Reputation: 34556
You don't need to hand-code your own JSON. Use json_encode()
echo json_encode($images);
To answer the question nonetheless, there's two ways of avoiding the trailing comma (which should indeed be removed, even if Firefox et al let you get away with it)
1 - conditionlise its output in your loop
$arr = array('apple', 'pear', 'orange');
foreach($arr as $key => $fruit) {
echo $fruit;
if ($key < count($arr) - 1) echo ', ';
}
Note this will work only for indexed arrays. For associative ones, you'd have to set up your own counter variable (since $key
would not be a number).
2 - remove it afterwards, e.g. with REGEX
$str = "apple, pear, orange, ";
$str = preg_replace('/, ?$/', '', $str);
Upvotes: 6