0

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?

3 Answers 3

1
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.

0

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

3
  • I think eval is more then enough in javascript :D Commented May 21, 2013 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. ;) Commented May 21, 2013 at 9:35
  • I see :D hahahaa I like json more the array :D Commented May 21, 2013 at 9:36
0

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

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.