Loop through each element under "Data" - php

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

Related

Echo an Array and make the content look pretty on the page

I am trying to echo out my array on each line, not bunched together.
I have tried <br />, this only show's on the front end, but when you look at HTML code. Its still clumped together.
$arrays = [];
$arrays[] = "Good";
$arrays[] = "Bad";
foreach ($arrays as $array){
echo $array;
}
Result:
GoodBad
Want Result:
Good
Bad
Short of using print_r, to quickly get your desired result, just make this small change:
echo $array."\n";
Make sure it's double-quotes and it will add a new line.
(That would do what "<br />" does on HTML)
Try using print_r($arrays). docs here.
Try echo "<pre>; var_dump($arrays); echo "</pre>;

PHP JSON foreach Array Issue

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

Multidimensional session php array echoing

I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}

How to parse a web service returned response into an array in PHP

I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}

How to print out the keys of an array like $_POST in PHP?

Maybe the code looks like something like this:
foreach(...$POST){
echo $key."<br/>;
}
var_dump($_POST);
or
print_r($_POST);
You might insert a pre tag before and after for the clearer output in your browser:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
And I suggest to use Xdebug. It provides an enchanted var_dump that works without pre's as well.
See the PHP documentation on foreach:
http://php.net/manual/en/control-structures.foreach.php
Your code would look something like this:
foreach ($_POST as $key=>$element) {
echo $key."<br/>";
}
Tested one liner:
echo join('<br />',array_keys($_POST));
If you want to do something with them programmatically (eg turn them into a list or table), just loop:
foreach ($_POST as $k => $v) {
echo $k . "<br>";
}
For debugging purposes:
print_r($_POST);
or
var_dump($_POST);
And if you want full coverage of the whole array, print_r or even more detailed var_dump
$array = array_flip($array);
echo implode('any glue between array keys',$array);
Or you could just print out the array keys:
foreach (array_keys($_POST) as $key) {
echo "$key<br/>\n";
}
Normally I would use print_r($_POST).
If using within an HTML page, it's probably worth wrapping in a <pre> tag to get a better looking output, otherwise the useful tabs and line breaks only appear in source view.
print_r() on PHP.net

Categories