Anthea Marie Anthea Marie - 2 months ago 8
JSON Question

Get values from JSON using PHP

Using an API token, I get the following JSON:

{"data": [
{"person_id": {
"name": "AAA",
"email": [;
{
"label": "work",
"value": "aaa@xxxcompany.cpm",
"primary": true
}
],
"phone": [
{
"label": "work",
"value": "05078945623",
"primary": true
}
]
}
}


I tried the following codes but it didn;t work

foreach ($object['data'] as $key => $value){

echo $value['person_id']['email']['value'];
echo $value['person_id']['phone']['value'];
}


How to get the email value: aaa@xxxcompany.com and phone value: 0507894562 in PHP?

I got the error:


Notice: Undefined index: value in C:\xampp\htdocs\pipedrive\index.php

on line 44

Notice: Undefined index: value in C:\xampp\htdocs\pipedrive\index.php

on line 45

Answer

Just follow the notation down the tree:

foo =  { "data": [
 |         |     |    { "person_id":
 |         |     |          |        {
 |         |     |          |          "name": "AAA",
 |         |     |          |          "email":   [
 |         |     |          |          |          |    { "label": "work"
 |         |     |          |          |          |         |
 |         |     |          |          |          |         |
foo    ['data']  [0]  ['person_id']    ['email']  [0]  ['label']

So

 JS:    foo.data[0].person_id.email[0].label        -> "work"
 PHP:   $foo->data[0]->person_id->email[0]->label   -> "work"

You forgot all of the arrays ([]) in there, and only handled the objects ({}).