48

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. Commented Sep 14, 2012 at 17:10
  • 3
    He might want to store encoded json somewhere for future use Commented Sep 14, 2012 at 17:15

2 Answers 2

105

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'];
Sign up to request clarification or add additional context in comments.

4 Comments

thanks brother, work out for me :) very easy and nice solution
How can i get value from this [{"countryId":"84","productId":"1","status":"0","opId":"134"}]
@151291 $json[0].countryId
@MihaiIorga the right solution is $json[0]->countryId, not $json[0].countryId because dot is user for string concatenation in php.
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...

Comments

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.