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

7ochem
  • 2,183
  • 1
  • 34
  • 42
waffl
  • 5,179
  • 10
  • 73
  • 123

2 Answers2

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.

7ochem
  • 2,183
  • 1
  • 34
  • 42
  • 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 '15 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);
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17