Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I need to create a keyed JSON array to pass a set of images that are queried via PHP to a vegas background slideshow which expects the images to be in an array like so:

$("#example, body").vegas({
    slides: [
        { src: "/img/slide1.jpg" },
        { src: "/img/slide2.jpg" },
        { src: "/img/slide3.jpg" },
        { src: "/img/slide4.jpg" }
    ]
});

I've tried manually building this as a string in PHP, setting it as a data attribute on a DOM object and getting it like so:

<div id="example" data-slides="[{ src: "1.jpg" }, {src: "2.jpg" }]"></div>

then:

slides: $('#example').data('slides');

Which doesn't work, as I imagine it is receiving a string, not an array.

I've tried using json_encode on an array such as [src=>"1.jpg", src=>2.jpg"] but am unable to get the correct formatting such as: { src: "img.jpg" }. I keep getting the entire string in the array:

["src=>\"1.jpg\"]

share|improve this question

2 Answers 2

up vote 3 down vote accepted

You should build your array in PHP like this:

$slides = array(
    array("src" => "/img/slide1.jpg"),
    array("src" => "/img/slide2.jpg"),
    array("src" => "/img/slide3.jpg"),
    array("src" => "/img/slide4.jpg")
);

echo json_encode($slides);

Which will output:

[{"src":"/img/slide1.jpg"},{"src":"/img/slide2.jpg"},{"src":"/img/slide3.jpg"},{"src":"/img/slide4.jpg"}]

You can indeed set the images JSON string as data (don't forget to HTML encode it):

<div id="example" data-slides="<?php
    echo htmlspecialchars(json_encode($slides));
?>"></div>

If you do $('#example').data('slides'); it will give you an array of objects as jQuery has recognized it as JSON and will parse it.

share|improve this answer
    
This worked perfectly, I think the key was array("src" => "/img/slide1.jpg") where obviously my silly mistake was pushing strings straight into the array and also not having htmlspecialchars() – waffl Jun 26 at 14:17

Not sure what the issue is...

$images = array("slides" => array()); // { slides: [] }
array_push($images["slides"], array("src" => "/img/slide1.jpg")); // { slides: [ { "src": "/img/slide1.jpg" } ] }
array_push($images["slides"], array("src" => "/img/slide2.jpg"));
array_push($images["slides"], array("src" => "/img/slide3.jpg"));
array_push($images["slides"], array("src" => "/img/slide4.jpg"));
echo json_encode($images);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.