How to access specific Element in Nested JSON Array in PHP?
I have a very large JSON file output from an API which has so many nested child elements, I have been trying to figure out a way to access only specific ones but it has been a total chaos and I finally gave up and came here looking for help.
here's what API return looks like:
{
response: {
errors : [],
messages : [],
results: {
candidates : [
{
count:{
from: 0,
to: 39,
total: 77,
},
officials: [
{
id: 10001,
first_name: John,
last_name: Doe,
office: {
id: 50001,
title: Head Office
}
},
{
id: 10002,
first_name: Mike,
last_name: Arthur,
office: {
id: 50005,
title: Secondary Office
}
},
]
}
]
}
}
}
PHP Code:
$request = wp_remote_get( 'MY URL' );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, JSON_PRETTY_PRINT );
if( ! empty( $data ) ) {
foreach( $data['response']['results']['candidates']['officials'] as $item) {
echo $item['last_name'];
}
}
I have also tried following:
$request = wp_remote_get( 'MY URL' );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, JSON_PRETTY_PRINT );
if( ! empty( $data ) ) {
foreach( $data-response-results-candidates-officials as $item) {
echo $item['last_name'];
}
}
Both solutions gives null.
What I need to get is only First Name Last Name of the candidate.
Thanks in advance :)
Topic wp-remote-get array json Wordpress
Category Web