Encode php array to use JSON array for use in javascript?
I need to create a JSON array with keys to pass a set of images that are requested via PHP in a Vegas style slideshow that expects the images to be in an array like this:
$("#example, body").vegas({
slides: [
{ src: "/img/slide1.jpg" },
{ src: "/img/slide2.jpg" },
{ src: "/img/slide3.jpg" },
{ src: "/img/slide4.jpg" }
]
});
I tried to manually create this as a string in PHP by setting it as a data attribute for the DOM object and getting it like this:
<div id="example" data-slides="[{ src: "1.jpg" }, {src: "2.jpg" }]"></div>
then
slides: $('#example').data('slides');
Which doesn't work, as I am assuming it is receiving a string and not an array.
I tried to use json_encode
in the array, such as [src=>"1.jpg", src=>2.jpg"]
, but could not get the correct format, for example { src: "img.jpg" }
. I keep getting the whole string in the array:
["src=>\"1.jpg\"]
source to share
You have to create 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);
The output will be:
[{"SRC": "/IMG/slide1.jpg"}, {"SRC": "/IMG/slide2.jpg"}, {"SRC": "/IMG/slide3.jpg"}, {"SRC" : "/IMG/slide4.jpg"}]
You can actually set the JSON string as data for the image (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 recognized it as JSON and will parse it.
source to share
I don't know what the problem 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);
source to share