json_encode() is corePHP function which is used to generate JSON which will be a simple value (i.e nethier an object nor an array). So, in this tutorial, we will see how to use json_encode() function to pass PHP array to Javascript.
![](http://findnerd.s3.amazonaws.com/imagedata/8895/8895.png)
PHP code:
<?php
$data = array(
array('name'=>'pankaj', 'email'=>'Pankaj@gmail.com'),
array('name'=>'Ayush', 'email'=>'Ayush@gmail.com')
);
?>
JavaScript Code:
<script>
getUserInfo(<?php echo json_encode($data); ?>)
function getUserInfo(userObj){
alert(JSON.stringify(userObj)); //convert object into string.
}
</script>
Code Explanation :-
In the above code, $data variable holds a multidimensional array which will pass to JavaScript with the help of json_decode().
<?php echo json_encode($data); ?>
Above line will convert $data array into simple values.
you can see the Javascript comment line, I have used one more function i.e JSON.stringify. JSON.stringify is Javascript function which is used to Convert JavaScript object into a string.
Output:
![](http://findnerd.s3.amazonaws.com/imagedata/8887/8887.png)
0 Comment(s)