3

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\"]

2 Answers 2

3

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.

1
  • 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() Commented Jun 26, 2015 at 14:17
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.