Encoding and Decoding JSON Data in PHP

Encoding JSON Data ( convert an array into JSON Data)

Lets say you have 5 variables :

a=1;

b=2;

c=3;

d=4;

e=5;

First you store these values in a associative array

<?php

$myArray = array(‘a’ => 1, ‘b’ => 2, ‘c’ => 3, ‘d’ => 4, ‘e’ => 5);

$json_data = json_encode ($myArray);

echo $json_data;

?>

Output :   { “a” : 1, ” b” : 2, “c” : 3, “d” : 4, “e” : 5 }

Decoding JSON Data ( Converting JSON Data into Array)

Lets say you a variable containing JSON data

$myVar=’ { “a” : 1, ” b” : 2, “c” : 3, “d” : 4, “e” : 5 } ‘;

<?php

$myArray= json_decode ($myVar , true);
var_dump($myArray);

?>

Output : array(5) { [“a”]=> int(1) [“b”]=> int(2) [“c”]=> int(3) [“d”]=> int(4) [“e”]=> int(5) }

Note : its an array of size 5.

To access value stored in c

<?  echo $myArray[‘c’]; ?>

output : 3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s