drwurqczo39355510 2016-08-31 07:46
浏览 43
已采纳

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

I'm using a token:

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

and here's the json text(not everything);

    {
     "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"
            }]
    }

I wanted to display "title" and I always get an error

Notice: Undefined index: creator_user_id in C:\xampp\htdocs\pipedrive\getjson.php on line 8

Here's my code so far:

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

I'm new to json so I'm just practicing and trying to figure out how to echo a specific value in php. Would be appreciated if you can explain exactly how it works when you echo from json to php.

Thank you! :)

  • 写回答

1条回答 默认 最新

  • doufeikuang7724 2016-08-31 08:04
    关注

    First of all you need to debug the array after using 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.
    ?>
    

    As per this array, you do not have title index inside the creator_user_id array. title is a separate index.

    Also note that, $object['data'] containing two indexes not one. you can get title as:

    <?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.
    }
    ?>
    

    Result:

    FFS Organization deal
    Google deal
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误