1

I've got a PHP array in this format:

        $js_data_array[] = array('href' =>$matches[1][0], //this is an image url
                                'title' =>'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
                                 );

And I need to get it into this format in javascript

 [{
'href' : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
},{
'href' : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}]

I'm using wp_localise_script() in wordpress to pass the data which doesn't seem to accept a json encoded array.

If I pass the array as is, I get a numerically indexed array with duplicate values of 'Array'

So, the question is, how can I pass the data as an array but without the numeric indexes? I can't have duplicate keys in a php array AFAIK.

3 Answers 3

1

see json_encode()

e.g.

$matches = array(1=>array(0=>'foo'));
$js_data_array = array();

$js_data_array[] = array(
'href' =>$matches[1][0], //this is an image url
  'title' =>'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
);
$js_data_array[] = array(
 'href' =>$matches[1][0], //this is an image url
  'title' =>'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
);

echo $json = json_encode($js_data_array);

prints

[{"href":"foo","title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit"},{"href":"foo","title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit"}]
Sign up to request clarification or add additional context in comments.

3 Comments

yeah thanks but I've tried that and can't use it with wp_localise_script()
When I log the the JSON output to the firebug console I get a string instead of an object e.g: "[{"href":"/files/2010/06/Bioreactor-4.jpg","title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit"},..... Is that because of the "?
From what I read here: weblogtoolscollection.com/archives/2010/05/07/… that's not how you use this wp_localise_script() anyway.
1

You should use the wp function wp_specialchars_decode() when decoding your json data :

wp_specialchars_decode($json, ENT_QUOTES)

Where $json is your encoded array.

Comments

0

It seems that wp_localize_script() encodes quotes. I therefore did a replace of " in the JS:

gallery_data = image.data.replace(/"/g,'"');

Comments

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.