在 Json 响应中访问数组 在 PHP 中通过 Invision 社区的 REST API 响应

我正在尝试从 Invision Community REST API 调用的 Json 响应内部访问“结果”数组。我不确定如何从 PHP 代码中过滤到结果数组,如下所示。一旦我过滤到它,我想将它回显到屏幕上,就像当前显示完整响应的方式一样。任何帮助将不胜感激!


PHP代码


<?php

    $communityUrl = 'https://website.net/invisioncommunity';

    $apiKey = 'apikey';

    $endpoint = '/core/members';


    $curl = curl_init( $communityUrl . 'api' . $endpoint );

    curl_setopt_array( $curl, array(

        CURLOPT_RETURNTRANSFER  => TRUE,

        CURLOPT_HTTPAUTH    => CURLAUTH_BASIC,

        CURLOPT_USERPWD     => "{$apiKey}:"

    ) );

    $response = curl_exec( $curl );

    $resArr = array();

    $resArr = json_decode($response);

    

    $resultsArr = cleanResponse($response);

    

    echo "<pre>"; print_r($resultsArr); echo "</pre>";    

    function cleanResponse($arr)

    {

        $element = $arr['results'];

        return $element;

    }

API 调用的 Json(部分)响应


{

    "page": 1,

    "perPage": 25,

    "totalResults": 111,

    "totalPages": 5,

    "results": [

        {

            "id": 1,

            "name": "Demo",

            "title": null,

            "timeZone": "America\/New_York",

            "formattedName": "Demo<\/span>",

            "primaryGroup": {

                "id": 4,

                "name": "Demo",

                "formattedName": "Demo<\/span>"

            },

            "secondaryGroups": [

                {

                    "id": 15,

                    "name": "Root Admin (Do not edit!)",

                    "formattedName": "Root Admin (Do not edit!)"

                }

            ],

            "email": "demo@website.net",

            "joined": "2020-07-07T19:48:33Z",

            "registrationIpAddress": "",

            "warningPoints": 0,

            "reputationPoints": 6,

            "photoUrl": "",

            "photoUrlIsDefault": false,

            "coverPhotoUrl": "",

            "profileUrl": "https:\/\/www.website.net\/profile\/1-demo\/",

            "validating": false,

            "posts": 3,


守着一只汪
浏览 67回答 1
1回答

繁华开满天机

对代码进行一些小更改应该可以解决您的问题:要获取返回的关联数组,请用作true第二个参数json_decode()$resArr = json_decode($response, true);使用关联数组$resArr作为函数的参数cleanResponse:$resultsArr = cleanResponse($resArr);现在$resultsArr保存results子数组,您可以使用例如输出print_r()
打开App,查看更多内容
随时随地看视频慕课网APP