1

I'm trying to use PHP to display some JSON data from an API. I need to use foreach to return all my results but nested within them is an array. The array is "highlights" which sometimes has "description" and sometimes "content" and sometimes both. I need to do a foreach within a foreach or something along those lines but everything I try just returns "Array".

Here's the JSON...

https://api.data.gov/gsa/fbopen/v0/opps?q=lte+test+bed+system&data_source=FBO&limit=100&show_closed=true&api_key=CTrs3pcYimTdR4WKn50aI1GcUxyL9M4s1fyBbSer

Here's my PHP...

$json_returned = file_get_contents("JSON_URL");
$decoded_results = json_decode($json_returned, true);

echo "Number Found:".$decoded_results['numFound']."</br> ";
echo "Start:".$decoded_results['start']."</br>";
echo "Max Score:".$decoded_results['maxScore']."</br>";

foreach($decoded_results['docs'] as $results){
echo "Parent Link T:".$results['parent_link_t']."</br>";
echo "Description:".$results['highlights']['description']."</br>";
}

Obviously the working version I'm using has a lot more fields programmed in but I cut them out to keep this code short and simple and show how I have everything else besides the "hightlights" field in one foreach. The JSON returns require that I keep everything in that foreach, so how to I display the array inside of it?

Thanks for any help and thanks for taking the time to read this even if you can contribute.

1
  • Tried what was recommended there but still no luck, perhaps it's something I'm doing wrong. All the same that's a great source of information and I appreciate you posting it! Commented Apr 25, 2016 at 6:54

2 Answers 2

1

The 'description' is array with one element so you can use this.

echo 'Description:' . $results['highlights']['description'][0];

If it sometimes has 'description' and sometimes 'content'. Use isset to check which one it is, or even if there are both and print accordingly.

// for description
if(isset($results['highlights']['description'])) {
   echo 'Description:' . $results['highlights']['description'][0];
}
// for content
if(isset($results['highlights']['content'])) {
   echo 'Content:' . $results['highlights']['content'][0];
}

Hope this helps.

0

Look into the php array_column() function: http://php.net/manual/de/function.array-column.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.