使用数组从API响应中检索id

时间:2017-08-23 08:34:24

标签: rest guzzle

您好我在我的应用程序中使用REST API来检索一些数据。我正在使用GuzzleHttp库。我对API的请求函数是:

public function createSurveyForCase()
    {

        $client = new Client(['base_uri' => 'http://localhost/survey/web/app_dev.php/api/']);
        $res = $this->client->request('POST', 'survey/', [
            'json' => [
                'base_survey_id' => 1,
                'client_trans_id' => '639252-2',
            ]
        ]);
        $survey = $res->getBody();

        return $survey;

    }

下面我展示了API的响应示例:

{
    "hash": "8537f99bb4166da9f74f02ebb70907cf",
    "sending_date": "2017-08-23T08:32:37+02:00",
    "expiration_date": "2018-02-23T08:32:37+01:00",
    "created_at": "2017-08-23T08:32:37+02:00",
    "trans_id": "10-550\r\n",
    "id": 18,
    "status": {
        "name": "new",
        "id": 1
    },
    "base_survey": {
        "name": "Base Survey Test 1",
        "created_at": "2017-07-25T10:08:18+02:00",
        "creator_trans_id": "10-615",
        "date_start": "2017-07-25T00:00:00+02:00",
        "expiration_int": 6,
        "expiration_string": "months",
        "survey_prefix": "PSI",
        "welcome_message": "test1",
        "expiration_message": "test2",
        "id": 1,
        "template": {
            "path": "/template_ssi_1/",
            "name": "SSI",
            "id": 1
        }
    }
} 

如何从此数据中检索id(值为18)?我试图这样做:

$survey["id"];
$survey->id;

但它没有工作

我认为它的工作方式与关联的PHP数组相似。

我会非常渴望得到帮助。 最好的问候

1 个答案:

答案 0 :(得分:0)

你可以做到

public function createSurveyForCase()
{

    $client = new Client(['base_uri' => 'http://localhost/survey/web/app_dev.php/api/']);
    $res = $this->client->request('POST', 'survey/', [
        'json' => [
            'base_survey_id' => 1,
            'client_trans_id' => '639252-2',
        ]
    ]);
    $survey = $res->getBody().toArray();

    return $survey;

}

然后像 $ survey [' id']

一样访问它