views:

35

answers:

2

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.

+1  A: 

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"}]
VolkerK
yeah thanks but I've tried that and can't use it with wp_localise_script()
codecowboy
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 "?
codecowboy
From what I read here: http://weblogtoolscollection.com/archives/2010/05/07/adding-scripts-properly-to-wordpress-part-2-javascript-localization/ that's not how you use this wp_localise_script() anyway.
VolkerK
A: 

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

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