Search code examples
phpgithubgithub-api

How can I get an object out of more than one JSON array in PHP?


I'm new to StackOverflow, so I apologize if I'm not formatting this correctly. I'm using the GitHub API and my goal is to get a list of a user's repositories in a dropdown form that they can select from.

Let's say the repository list URL is https://api.github.com/users/MY_GITHUB_USERNAME/repos (The way I sat things up I can get the repo URL by doing $userdata->repos_url). When I use the following:

$curl1 = curl_init();
        curl_setopt($curl1, CURLOPT_URL, $userdata->repos_url);
        curl_setopt($curl1, CURLOPT_HEADER, 0);
        curl_setopt($curl1, CURLOPT_HTTPHEADER, array(
        'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth'
    ));
        curl_setopt($curl1,CURLOPT_USERAGENT,'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth');
        curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);  
        curl_setopt($curl1, CURLOPT_SSL_VERIFYHOST, 0);
    $cont1 = curl_exec($curl1);
    curl_close($cont1);
    echo $cont1;

It responds with the following:

[
  {
    (information I don't need)
    "full_name": "github-username/this-is-what-i-want",
    (information I don't need)
  }
]

I only have one repository at the moment. What I want to do is make a code that echos only the full_name and if there's more than one array echo each one. (All arrays will have full_name.)

Does anyone know how I could do this?


Solution

  • Decode it to an array, then loop through the arrays until you get to what you want:

    $data=json_decode($cont1, true);  <~~~ tells php to decode the JSON into an array
    
    $results=$data['FirstArray']['SecondArray']['NumResultsReturned']; <~~ most JSON's have a value showing how many arrays got sent back to you in the results.  You didn't give a true data example as a reply, so can't give exacts on these fields for you.