Anthea Marie Anthea Marie - 3 months ago 8
JSON Question

How to access specific value in php and 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! :)

Answer

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