【问题标题】:How can I get an object out of more than one JSON array in PHP?如何从 PHP 中的多个 JSON 数组中获取一个对象?
【发布时间】:2021-11-07 15:06:54
【问题描述】:

我是 StackOverflow 的新手,所以如果我的格式不正确,我深表歉意。我正在使用 GitHub API,我的目标是在用户可以从中选择的下拉表单中获取用户存储库的列表。

假设存储库列表 URL 是 https://api.github.com/users/MY_GITHUB_USERNAME/repos(我坐下来的方式是通过执行 $userdata->repos_url 来获取存储库 URL)。当我使用以下内容时:

$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;

它的响应如下:

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

我目前只有一个存储库。我想要做的是制作一个只回显full_name 的代码,如果有多个数组回显每个。 (所有数组都有full_name。)

有人知道我该怎么做吗?

【问题讨论】:

    标签: php github github-api


    【解决方案1】:

    将其解码为一个数组,然后遍历数组,直到得到你想要的:

    $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.
    
    $i=0;
    while ($i < $results) // loop through the arrays.
    {
    // Do stuff with your arrays, either ignore if non-important or capture to variables / display if you want it).
    ++$i;
    }
    

    【讨论】:

    • 感谢您的回复!抱歉,我不够清楚,您的方法可能有效,但似乎没有命名 JSON 数组。 Here's the full JSON in question,但是用户可能拥有多个 Github 存储库,因此它可能显示多个数组。我正在寻找的是从所有数组中获取full_name
    • 每个说“id:”、“node_id:”、“full_name:”等的部分都可以在转换为数组后由该标识符调用。要进入数组,因为没有顶级标识符,您只需使用 [#NumOfArraySection] 即开始您可以使用 $id = $results[0][id]; $nodeid = $results[0][nodeid];要深入研究某些子数组,您可以使用类似 $followers_url = $results[0][owner][followers_url];如果您正在循环,您将在我的示例中使用 $i 来获取每个数组中的相同记录。 $results[$i][id] 等
    猜你喜欢
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多