I have php array like this
[0]->imgae_name=1
image_url=a
[1]->imgae_name=2
image_url=b
i want to convert this array in javascript array how can i do this?
asked May 21, 2013 at 9:27
Sonil Gandhi
1791 silver badge11 bronze badges
3 Answers 3
json_encode($your_array);
is the right way to do this. It converts your php array to this string:
[{imgae_name:1,image_url:"a"},{imgae_name:2,image_url:"b"}]
Then you only have to assign it to a variable in a script tag.
answered May 21, 2013 at 9:28
bwoebi
23.8k5 gold badges64 silver badges81 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You could convert the PHP array to JSON using json_encode, then echo the json string into the Javascript in your page and use Javascript JSONObject to convert it into a JS array
answered May 21, 2013 at 9:29
fullybaked
4,1271 gold badge26 silver badges37 bronze badges
3 Comments
Jeff Lee
I think eval is more then enough in javascript :D
fullybaked
@JeffLee not to split hairs, but doesn't eval() return an Object not an Array? I know the difference is little, but just going with the OP's question here. ;)
Jeff Lee
I see :D hahahaa I like json more the array :D
In php
<?
$array = array("A" => "1", "B" => "2");
echo json_encode($array);
?>
In Javascript
var mObject = eval("(" + phpecho + ")");
Then you can access the value :
mObject.A // 1
Comments
default