简体   繁体   中英

How do i access data from an array with json data in PHP

Hi guys i have been working with an api and they return a response like this. I am really confused on here cause i have tried accessing it like any other json data but it's returning an attempt to read error

[ { "service": 1, "name": "Followers", "type": "Default", "category": "First Category", "rate": "0.90", "min": "50", "max": "10000", "refill": true, "cancel": true }, { "service": 2, "name": "Comments", "type": "Custom Comments", "category": "Second Category", "rate": "8", "min": "10", "max": "1500", "refill": false, "cancel": true } ]

this is my api request

$api_key = "myapikey"; $link = "httpsaddresshere";

$params = [
    'key' => $api_key,
    'action' => 'services'
];

$url = curl_init($link);
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POST, 1);
curl_setopt($url, CURLOPT_POSTFIELDS, $params);

$exec = curl_exec($url);
$result = json_decode($exec);

echo $result->name;

Api is working fine i am seeing result when i use var_dump; but it returns an error trying to access the data

This is because the JSON returned is an array of objects. Thus, while passing it into json_decode you would get the array of objects:

Doing this: print_r($result); would produce an output like:

Array
(
    [0] => stdClass Object
        (
            [service] => 1
            [name] => Followers
            [type] => Default
            [category] => First Category
            [rate] => 0.90
            [min] => 50
            [max] => 10000
            [refill] => 1
            [cancel] => 1
        )

    [1] => stdClass Object
        (
            [service] => 2
            [name] => Comments
            [type] => Custom Comments
            [category] => Second Category
            [rate] => 8
            [min] => 10
            [max] => 1500
            [refill] => 
            [cancel] => 1
        )

)

Thus to access it you should replace:

$result->name with $result{0}->name

Or better if:

$result = json_decode($exec, true);

Would convert it into an array, thus access it as:

$result[0]['name'];

Just iterate on the result and get the response:

foreach($result as $res){
   
   //if result is array
   echo $res['name'];

   //if result is object
   echo $res->name;

}

You can use

$result = json_decode($exec, true)

and the can access the array values by their key name like

$result[0]['service']
//shall out put followers

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