Encode php array to keyed JSON array for use in javascript?

118 views Asked by At

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

There are 2 answers

1
7ochem On BEST ANSWER

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.

0
Sebastian Nette On

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