sdot257
sdot257

Reputation: 10366

How to parse this JSON in PHP?

It's stored inside MongoDB and passed to my view file with json_decode.

Using PHP, how can I grab the values from within?

"environment" : {
            "_id" : "QU",
            "name" : "QA Unstable",
            "streams" : "unstable",
            "hosts" : [
                    "deployclient1",
                    "deployclient2"
            ]
}

Upvotes: 1

Views: 224

Answers (3)

Sammaye
Sammaye

Reputation: 43884

Now to actually answer the question since you already know of json_decode:

Using PHP, how can I grab the values from within?

json_decode will evaluate the JSON string into a object in PHP (by default) which means you can use basic dynamic accession syntax to get to your values, i.e. to get _id:

$object->environment->_id;

Or a host:

$object->environment->hosts[0]

That will return: deployclient1

Upvotes: 3

Michael Blake
Michael Blake

Reputation: 125

Don't forget to wrap the string in curly braces...

$str = '{"environment" : {
            "_id" : "QU",
            "name" : "QA Unstable",
            "streams" : "unstable",
            "hosts" : [
                    "deployclient1",
                    "deployclient2"
            ]
}}';

print_r(json_decode($str, true));

Upvotes: 1

Ranty
Ranty

Reputation: 3362

Use $array = json_decode($json_string, TRUE);. Second variable makes it array if you supply TRUE or object if you omit it.

Upvotes: 4

Related Questions