简体   繁体   English

从奇怪的JSON数组响应中提取数据

[英]Pulling data from weird JSON array response

I am working with an API and the response comes back weird. 我正在使用API​​,响应返回很奇怪。 I need to grab the ID field from the response below. 我需要从下面的响应中获取ID字段。

{
    "message_campaigns": [
        {
            "embedded_errors": [],
            "id": "2729",
            "is_legacy_message": false,
            "is_setup_complete": false,
            "message_campaign_type_id": 1,
            "name": "Message Campaign 1",
            "organization_id": 123
        }
    ]
}

Below is my attempt: 以下是我的尝试:

$result = curl_exec($ch);
curl_close($ch);  // Seems like good practice
$responseData = json_decode($result, TRUE);
print_r($responseData);

I have tried several methods and cannot get it to work 我尝试了几种方法,但无法正常工作

$responseData[0]['id'];
$responseData->id;

I can't figure out how to get the id to display. 我不知道如何获取id来显示。

It's because the result is an array , as you pass the second parameter as true to json_decode : 这是因为结果是一个array ,当您将第二个参数true传递给json_decode

When TRUE, returned objects will be converted into associative arrays. 如果为TRUE,则返回的对象将转换为关联数组。

In JSON, {} stands for objects, and [] stands for array. 在JSON中, {}代表对象, []代表数组。 You've converted all objects to associative arrays, so this'll work: 您已将所有对象转换为关联数组,因此可以正常工作:

$responseData['message_campaigns'][0]['id']

You have the second parameter of json_decode set to true , so an array (not an object) will be returned. 您已将json_decode的第二个参数设置为true ,因此将返回一个数组(不是对象)。

You'll also need to access message_campaigns as the first item in the array. 您还需要访问message_campaigns作为数组中的第一项。

$responseData['message_campaigns'][0]['id'];

This can be tested: 可以测试:

$result = <<< EOT
{
    "message_campaigns": [
        {
            "embedded_errors": [],
            "id": "2729",
            "is_legacy_message": false,
            "is_setup_complete": false,
            "message_campaign_type_id": 1,
            "name": "Message Campaign 1",
            "organization_id": 123
        }
    ]
}
EOT;

$responseData = json_decode($result, TRUE);

echo $responseData['message_campaigns'][0]['id'];
// 2729

Assuming your curl_exec actually returns a response because you've set curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 假设您的curl_exec实际上返回了响应,因为您已设置curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

If I look at your json response you need: 如果我查看您的json响应,则需要:

$responseData['message_campaigns'][0]['id'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM