Search code examples
phparraysjsoncurlresponse

JSON decode in php web programming


I am facing a problem in php using CURL. I made a https request and I got response in multidimesional array.

[{  
 "id":"22622",
 "name":"",
 "email":"[email protected]",
 "mobileno":"",
 "birth_dt":"",
 "marital_status":"",
 "gender":"",
 "educationid":"0",
 "occupationid":"0",
 "industryid":"0",
 "incomeid":"",
 "city":"0",
 "state":"0",
 "country":"0",
 "postcode":"",
 "deviceid":"805086099499488",
 "regid":"",
 "device_type":null,
 "userstatus":"0",
 "refcode":"D1219C92",
 "new_user":"0",
 "device_token":""
 }]

Now I want to decode it and save the value of "id" in a variable.

$result=curl_exec($ch);
$books = json_decode($result, true);
echo ($books[0]['id']);

I tried the above code, but failed.


Solution

  • You need to use foreach() loop for this.

    foreach ($a[0] as $key => $value) {
    echo $key."<br>".$value;
    if($key == 'id'){
        $id = $value;
    }
    }
    
    echo $id;
    

    Also, if you just want to assign the value of id to another variable, you can just right

    ...
    $no = $a[0]->id;
    echo $no
    ...
    

    instead of the foreach loop.