44

I have an url passing parameters use json_encode each values like follow:

$json = array
(
    'countryId' => $_GET['CountryId'],
    'productId' => $_GET['ProductId'],
    'status'    => $_GET['ProductId'],
    'opId'      => $_GET['OpId']
);

echo json_encode($json);

It's returned a result as:

{  
  "countryId":"84",
  "productId":"1",
  "status":"0",
  "opId":"134"
}

Can I use json_decode to parse each values for further data processing?

Thanks.

George G
  • 7,443
  • 12
  • 45
  • 59
conmen
  • 2,377
  • 18
  • 68
  • 98

2 Answers2

103

json_decode() will return an object or array if second value it's true:

$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
25

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Vladimir Hraban
  • 3,543
  • 4
  • 26
  • 46