Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 0 down vote accepted

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

share|improve this answer
 
I think eval is more then enough in javascript :D –  Jeff Lee May 21 '13 at 9:32
 
@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. ;) –  fullybaked May 21 '13 at 9:35
 
I see :D hahahaa I like json more the array :D –  Jeff Lee May 21 '13 at 9:36
add comment
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.

share|improve this answer
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.