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\"]
You should build your array in PHP like this:
Which will output:
You can indeed set the images JSON string as data (don't forget to HTML encode it):
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.