JSON Decode (PHP)

how can i select the value of "success" from this json ?:

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

}
}

Here is my current code:

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

Thank. Relationship

+4
source share
2 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 :: Processing a value successin 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...
        }
+4
source

You are almost close to a solution. place " true " as the second argument to json_decode().

For instance:

$result = json_decode ($json, true);
$result['response']['success'];`  -> to get the value of success.
+3
source

Source: https://habr.com/ru/post/1660579/


All Articles