I'm working with the following JSON Object:
{
"body": {
"subject": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"to": [
{
"location": "Hawthorne, CA",
"name": "Jeff Daniels",
"phoneNumber": "+15552123456",
"target": true
}
],
"type": "SMS"
},
"uuid": "5797377010673708914"
}
I'm trying to retrieve certain values and can't work out the syntax to get the to phoneNumber value. Here's what I'm doing so far:
$webhook= json_decode( $webhookJSON, TRUE );
$subject = $webhook['body']['subject'];
$toPhoneNumber = $webhook['body']['to']['phoneNumber'];
I'm getting the $subject
but not the $toPhoneNumber
. I've tried adding [0]
in a few places to get the first member of the array but this isn't working either and at this stage I'm stumped as to how I can get the to phoneNumber value from the nested array.
My Answer:
To retrieve the phoneNumber value from the nested array 'to', you need to access it as an array element since 'to' is an array with one element. Here's the correct syntax to retrieve the phoneNumber value:
php
$webhook = json_decode($webhookJSON, TRUE);
$subject = $webhook['body']['subject'];
$toPhoneNumber = $webhook['body']['to'][0]['phoneNumber'];
echo $subject; // Output: Lorem ipsum dolor sit amet, consectetur adipiscing elit
echo $toPhoneNumber; // Output: +15552123456
By adding `[0]` after `['body']['to']`, you are accessing the first element of the 'to' array, and then you can access the 'phoneNumber' value from that element.
Rate this post
4 of 5 based on 5495 votesComments