PHP JSON foreach Array Issue - php

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.

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.

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

Related

Loop through each element under "Data"

I'm using Kucoin's API to get a list of coins.
Here is the endpoint: https://api.kucoin.com/v1/market/open/coins
And here's my code:
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print_r($kucoin_coins);
I can see how to target one coin like so:
echo "name: " . $kucoin_coins['data'][0]['name'];
But I can't see how to loop through them.
How can I loop through each of the "coins" returned here? They are under the "data" part that is returned. I'm sorry, I'm just not seeing how to do it right now. Thank you!
You can loop through the decoded elements using the foreach command:
foreach ($kucoin_coins['data'] as $coin) {
//do your magic here.
}
But I usually prefer using json_decode($kucoin_coins) rather than the one for arrays. I believe this:
$item->attribute;
Is easier to write than this one:
$item['attribute'];
foreach($kucoin_coins['data'] as $data) {
echo $data['name']."\n";
}
You can loop through your data using foreach() like this
<?php
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print '<pre>';
print_r($kucoin_coins);
print '</pre>';
foreach($kucoin_coins['data'] as $key=>$value){
echo $value['name']. "<br/>";
}
?>
See DEMO: http://phpfiddle.org/main/code/q6kt-dctg

get all data from a variable

if i want to see what data is available into a variable, i fetch the data like ---
get(0) to get the first data like 'www.hello.com/23/23', get(1) to get the second data like 'www.mydomain.com/it/12', and so on ....
$apartmentId = $user->getApartment()->get(0)->getId();
Now if there are more data available in the getApartment(), which method i should use to get all the id's which is available in getApartment() !
i Have tried getAll() method which dose not working in this case. Anyone have any idea how to solve this problem. Thanks in advanced .
One way to get all values, is to use a foreach() loop.
<?php
$var = array(
'value_One',
'value_Two',
'value_Three',
'value_Four',
'value_Five'
);
foreach($var AS $value){
echo $value . "<br>";
}
?>

foreach $_POST as $value create

I just started learning PHP and I am having some difficulties with some of the coding.
Hopefully, someone could help me a little.
I'm using this:
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1) {
echo " $a1";}}
The echo will write several results of $a1 depending on how many were selected in the form.
What I want is to save those results to some values so I can add them in MySQL.
Something like this:
if(!empty($_POST['yyy']))
{
foreach($_POST['yyy'] as $a1)
{
echo " $a1"; where $a1 will create a $result1,$result2,$result3(for each isset)
}
}
Then if I use:
echo "$result2";
it will give me the second result.
Not clear whether you are asking about this kind of result or not. But you can use an array to store each values inside the foreach loop.
var data=[];// define an array to access outside of if statement later..
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1){
data[]=$a1;
//or can use array_push() method
array_push(data,$a1);
}
}
/*this will give the second result(because array indexing starts from 0. So to get third result
use data[2])*/
echo data[1];
Furthermore by echoing quoted variable will not give the value of that variable but gives a string literal.
echo "$result2" //output---> $result

How to get data from array [API/JSON]

I'm currently trying to get going with API's but i'm finding it really hard to extract the data from the api into my webpage.
I have tried using json_decode($, true), and it works OK, but some data I just cant extract.
Like, in this example, how would you get the name?
{"id":12345678,"name":"MyAwesomeLeagueName","profileIconId":593,"summonerLevel":30,"revisionDate":1389164617000}
I have used for getting data from others, but cant really get it to work with types like this one.
//put json in array
$r = json_decode($r, true);
echo $r['champions'][1]['attackRank'];
Also, if anyone have some good JSON -> PHP Tutorials I would really appreciate.
In that example to access the name you just need to refer to $r['name'] e.g.
echo $r['name'];
After decoding the JSON string, do a var_dump on your array and it will show you the contents and how to access.
To get all with a certain magic rank as per your example, you'd need to loop through the array and test the value of the particular key:
$r = json_decode($r, true);
//loop through $r
foreach ($r['champions'] as $key => $value) {
if ($value['magicRank'] != 8) {
//if magicRankis not 8, ignore and move on to the next entry
continue;
}
//magicRank is 8, do something
echo $value['name'] . " has magic rank of 8<br />";
}

How to get specific instance in PHP array?

I am trying to get the specific value of file extension in this array. All I can do so far is .
I am wanting the fileextention ".jpg"
All I know how to do is echo the values like so using foreach;
file_nameBob7213.jpg file_typeimage/jpeg
file_pathC:/xampp/htdocs/midas/records/
full_pathC:/xampp/htdocs/midas/records/Bob7213.jpg raw_nameBob7213
orig_nameBob72.jpg client_nameafasfafs.jpg **file_ext.jpg** file_size44.96
is_image1 image_width716 image_height474 image_typejpeg
image_size_strwidth="716" height="474"
I am only interested in retrieving the file_ext from this array. How do I select that exact thing?
foreach ($file['upload_data'] as $item => $value)
{
echo $item; echo $value; echo "<br/>";
}
How do I do this? , thanks!
$file['upload_data']['file_ext']
It's just an array within an array, so specify 2 array keys
Incidentally, if you want to see the contents of an array, a quick way of doing it is to use var_export:
var_export($file); # echoes the entire array
You don't need to write a foreach loop every time
$file['upload_data']['file_ext'] contains '.jpg'.

Categories