简体   繁体   中英

Extract JSON Data with PHP

Suppose below is my JSON data

{"pricing": {
     "com": {
         "addons": {
                "dns": true,
                "email": true,
                "idprotect": true
       },
     "org": {
         "addons": {
                "dns": true,
                "email": true,
                "idprotect": true
       },
     "net": {
         "addons": {
                "dns": true,
                "email": true,
                "idprotect": true
       }
}}

I want to display only (com, org, net) from above JSON. How can we do that?

An option to do this is to use json_decode and pass true for the second parameter to convert the returned objects into associative arrays.

To display only the keys you could loop $output["pricing"] using a foreach and display the keys:

$json = '{"pricing": {"com": {"addons": {"dns": true,"email": true,"idprotect": true}},"org": {"addons": {"dns": true,"email": true,"idprotect": true}},"net": {"addons": {"dns": true,"email": true,"idprotect": true}}}}';
$output = json_decode($json, true);

foreach ($output["pricing"] as $key => $value) {
    echo $key . "<br>";
}

Another way could be to get the array_keys and loop them:

foreach (array_keys($output["pricing"]) as $key) {
    echo $key . "<br>";
}

First u had a incorrect JSON format check it out. I think this solution might help you!!

$json = '{"pricing": {"com": {"addons": {"dns": true,"email": true,"idprotect": true}},"org": {"addons": {"dns": true,"email": true,"idprotect": true}},"net": {"addons": {"dns": true,"email": true,"idprotect": true}}}}';
$output = json_decode($json);

print_r($output->pricing->com->addons);
print_r($output->pricing->org->addons);
print_r($output->pricing->net->addons);

You will get something like this !!

stdClass Object ( [dns] => 1 [email] => 1 [idprotect] => 1 ) 
stdClass Object ( [dns] => 1 [email] => 1 [idprotect] => 1 ) 
stdClass Object ( [dns] => 1 [email] => 1 [idprotect] => 1 )

Are you looking for this ??

 $json = '{"pricing": {"com": {"addons": {"dns": true,"email": true,"idprotect": true}},"org": {"addons": {"dns": true,"email": true,"idprotect": true}},"net": {"addons": {"dns": true,"email": true,"idprotect": true}}}}';
$output = json_decode($json,true);

echo implode(",",array_keys($output["pricing"]));

com,org,net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM