Reputation: 10114
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.
Upvotes: 1
Views: 195
Reputation: 11
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.
Upvotes: 1
Reputation: 10114
It seems that wp_localize_script() encodes quotes. I therefore did a replace of " in the JS:
gallery_data = image.data.replace(/"/g,'"');
Upvotes: 0
Reputation: 96189
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"}]
Upvotes: 1