Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Decode (PHP)

Tags:

json

php

decode

how can I Select the value of "success" from that json?:

{
"response": {
    "success": true,
    "groups": [
        {
            "gid": "3229727"
        },
        {
            "gid": "4408371"
        }
    ]

}
}

Thats my current code:

$result = json_decode ($json);
$success = $result['response'][0]['success'];
    echo $success;

Thank you. Regards

like image 923
Enge Avatar asked Mar 10 '23 16:03

Enge


1 Answers

Here You go... with a Quick-Test Here:

    <?php

        $strJson    = '{
            "response": {
                "success": true,
                "groups": [
                        {
                            "gid": "3229727"
                        },
                        {
                            "gid": "4408371"
                        }
                    ]
                }
            }';


        $data       = json_decode($strJson);
        $success    = $data->response->success;
        $groups     = $data->response->groups;

        var_dump($data->response->success); //<== YIELDS::      boolean true
        var_dump($groups[0]->gid);          //<== YIELDS::      string '3229727' (length=7)
        var_dump($groups[1]->gid);          //<== YIELDS::      string '4408371' (length=7)

UPDATE:: Handling the value of success within a Conditional Block.

    <?php

        $data       = json_decode($strJson);
        $success    = $data->response->success;
        $groups     = $data->response->groups;

        if($success){
             echo "success";
             // EXECUTE SOME CODE FOR A SUCCESS SCENARIO...
        }else{
             echo "failure";
             // EXECUTE SOME CODE FOR A FAILURE SCENARIO...
        }
like image 63
Poiz Avatar answered Mar 20 '23 15:03

Poiz