如何在php和json中访问特定值

时间:2016-08-31 07:46:27

标签: php json

我正在使用令牌:

$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";

这里是json文本(不是所有内容);

    {
     "success":true,
     "data":[{
            "id":1,
            "creator_user_id":{
                        "id":1682756,
                        "name":"Kamilah",
                        "email":"kamilah@fractal.ae",
                        "has_pic":false,
                        "pic_hash":null,
                        "active_flag":true, 
                        "value":1682756},
                        "title":"FFS Organization deal"
            }]
    }

我想显示“标题”,我总是收到错误

  

注意:未定义的索引:creator_user_id in   第8行的C:\ xampp \ htdocs \ pipedrive \ getjson.php

到目前为止,这是我的代码:

$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";

$response = file_get_contents($url);
$object = json_decode($response, true);

echo $object['data']['creator_user_id']['title'];

我是json的新手,所以我只是练习并试图找出如何回应php中的特定值。如果你能从json回复到php,你可以准确地解释它是如何工作的,将不胜感激。

谢谢! :)

1 个答案:

答案 0 :(得分:0)

首先,您需要在使用json_decode()后调试数组。

<?php
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";

$response = file_get_contents($url);
$object = json_decode($response, true);
echo "<pre>";
print_r($object); // this will print all data into array format.
?>

根据此数组,title数组中没有creator_user_id索引。 title是一个单独的索引。

另请注意,$object['data']包含两个索引而不是一个。你可以得到title

<?php
foreach ($object['data'] as $key => $value) {
    //print_r($value); // this will print the values inside the data array.
    echo $value['title']."<br/>"; // this will print all title inside your array.
}
?>

<强>结果:

FFS Organization deal
Google deal