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.

2
  • 1
    ...What? You're not seriously trying to json_encode something in PHP, then json_decode it later in the same PHP? I'm so confused. Sep 14, 2012 at 17:10
  • 3
    He might want to store encoded json somewhere for future use Sep 14, 2012 at 17:15

2 Answers 2

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'];
4
  • thanks brother, work out for me :) very easy and nice solution Feb 8, 2015 at 8:37
  • How can i get value from this [{"countryId":"84","productId":"1","status":"0","opId":"134"}] Mar 24, 2017 at 12:48
  • 2
    @151291 $json[0].countryId Mar 24, 2017 at 23:23
  • 4
    @MihaiIorga the right solution is $json[0]->countryId, not $json[0].countryId because dot is user for string concatenation in php. Feb 15, 2019 at 11:27
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...

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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