简体   繁体   中英

php json object reading

I have a web page written in php where i get some info about the user from his linked in profile, thanks to linked in API. It gives me the following json object. with :

$user = json_decode($response);

method i decode the following json object into $user object.

{ "firstName": "Tolga", "lastName": "Evcimen", "skills": { "_total": 2, "values": [ { "id": 1, "skill": {"name": "Microsoft Office"} }, { "id": 2, "skill": {"name": "Microsoft Excel"} } ] } }

what i can't is to work with these values, my php knowledge is a little low, that's why i don't know how to read skills or anything else. The only thing I could read so far is :

$user->firstName , $user->lastName

but I can't get the rest with same approach :(

$user->skills->values[1]->skill->name, or $user->skills->_total

please give me some information about these things

This works:

echo $user->firstName;
echo $user->skills->values[0]->id;
echo $user->skills->values[0]->skill->name;

Results:

Tolga
1
Microsoft Office

Test it on PHP fiddle: http://phpfiddle.org/main/code/x18-z6f

I had no problem with this, maybe post a code example so we can see where you went wrong.

$user->skills->values[1]->skill->name

Example:

<?php
    $response = '{
      "firstName": "Tolga",
      "lastName": "Evcimen",
      "skills": {
        "_total": 2,
        "values": [
          {
            "id": 1,
            "skill": {
              "name": "Microsoft Office"
            }
          },
          {
            "id": 2,
            "skill": {
              "name": "Microsoft Excel"
            }
          }
        ]
      }
    }';

    $user = json_decode($response);

    var_dump($user->skills->values[1]);

?>

Output:

object(stdClass)#5 (2) {
  ["id"]=>
  int(2)
  ["skill"]=>
  object(stdClass)#6 (1) {
    ["name"]=>
    string(15) "Microsoft Excel"
  }
}

thanks a lot, it turned out I made some other mistakes in the code, instead of echo I used print, and kinda mixed it up in a bad way. thats why I couldn't achive the right behaviour in code.

$user = fetch('GET', '/v1/people/~:(firstName,lastName,skills)');
print "\n <\br> Hello $user->firstName $user->lastName."; 
print " $user->skills->values[0]->skill->name";
echo $user->skills->values[0]->skill->name;
exit; 

doesn't work :)

echo "\n <\br> Hello $user->firstName $user->lastName.";  
echo $user->skills->values[0]->skill->name;

works fine.

Grateful for your concerns.

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