Getting nested array data from JSON - php

I am currently trying to retrieve some info from some json code in PHP. I have some of it achieved but I am trying to get a players name from a nested array and I am having a bit of trouble. This is the json info:
Sorry I had to post on pastebin as JSON wouldnt embed in the code box. ht
tps://pastebin.com/6RZAgKFa
I have pulled in the info like so:
$json_string2 = 'URL TO JSON DATA';
$jsondata2 = file_get_contents($json_string2);
$serverinfo2 = json_decode($jsondata2,true);
And I can view it by printing it.
Now I am trying to loop through it all to just retrieve names, I am trying the following:
foreach($serverinfo2 as $playerinfo) {
foreach($playerinfo as $playerstuff) {
echo $playerstuff;
}
}
But that returns the full array. I then add [name] to the end of echo $playerstuff and it returns a number 1 and a D. Not even relevant, and $playerstuff->name also doesn't work. Can anyone help me at all. Thanks :)

You can try this to achieve data from nested data from json :
<?php
$res = '[{"endpoint":"127.0.0.1","id":"2","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Deadpool","ping":"85"},{"endpoint":"127.0.0.1","id":"1","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Logan","ping":"73"}]';
$result = json_decode($res,true);
// echo '<pre>'; //print_r($result);
foreach ($result as $key => $value) {
// print_r($value);
echo $endpoint = 'endpoint : ' .$value['endpoint'];echo "<br/>";
echo $name = 'name :' .$value['name'];echo "<br/>";
}
?>

Related

How do I display data from cURL into a table in PHP?

I need to get data from a website and display in a table in my website. I am getting the data correctly but now just need to add it to a table so that it is more legible.
This is the code for some of the information I am getting:
echo "<div style='font-weight: bold;'>getProvinces</div>";
$args = array();
$args["strSessionId"] = $session;
$result = CurlFunction($args, "getProvinces");
echo '<pre>';
var_dump($result);
echo '</pre>';
And
case "getProvinces":
{
$Url = "https://apitest.axxess.co.za/" .
"calls/rsapi/getProvinces.json";
$curl->setBasicAuthentication($Username, $Password);
$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
$curl->setOpt(CURLOPT_SSL_VERIFYHOST,2);
$curl->get($Url, $d);
break;
}
I just need some help on how to get the above info into a table. And if possible only sections. I have attached an image to show what I am getting at the moment as well as which data I would like to have in a Table format.
Thanks
Link to complete code I am using: https://transfernow.net/923hx9h1f2er
Use json_decode to obtain an array representing your response data, and use a foreach loop to create key-value pairs inside a table for each data item.
The code could look like:
$jsoned = json_decode($result, true)
?>
<table>
<?php foreach ($jsoned as $k => $v) {?>
<tr><td> <?=$k?> </td><td> <?=$v?> </td></tr>
<?php } ?>
btw, <?= $var ?> is a shortcut for <? echo $var; ?>
First of all, convert your json response into an array by using json_decode() like:
// assuming `$jsonResponse` is your json response variable
$decoded = json_decode($jsonResponse,true); // here true will use return response in array format
Then, you can use your response check like:
if($decoded['intCode'] == 200){
print_r($decoded['arrProvinceId']); // this will return you your response in array
}
now, you can you foreach() loop with html whatever you need with $decoded['arrProvinceId'] result.

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

Unable to ECHO PostgreSQL Query Results - PHP

I've successfully connected to a PostgreSQL database and even the query is running successfully.
But when I try to print the data using this code echo $data I get error as Array to String Conversion.
Tried searching in the forum and google. Nothing was fruitful.
Please help me.
Code used to convert it to array and print it.
if ( ! $myquery ) {
echo pg_error();
die;
}
$data = array();
for ($x = 0; $x < pg_num_rows($myquery); $x++) {
$data[] = pg_fetch_assoc($myquery);
}
// echo json_encode($data);
// $data2 = array_shift($data);
echo $data;
pg_close($server);
Read the error :
Array to String Conversion
Try to display it using var_dump or print_r because it's an array.
The error says that you want to display an array with echo which can only display string.
exemple : var_dump($data);
To just print the array (for debuging) use var_dump() like this:
var_dump($data)
But if you want to echo every line in the array you have to loop:
foreach ($data as $row) {
echo $row;
}
You are pinting array with echo.Try print_r(); that will print array. Like this print_r($data);
Try using var_dump($var) or print_r($var) functions

Domain index checking using Google API

I am trying to build website where a user can enter his website and check his indexed pages in google.
Just like we do by site:domain.com
I am using a google API, here is the link to API (I know it's deprecated)
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=
when I use a code like
<?php
function getGoogleCount($domain) {
$content = file_get_contents('http://ajax.googleapis.com/ajax/services/' .
'search/web?v=1.0&filter=0&q=site:' . urlencode($domain));
$data = json_decode($content);
return ($data->responseData->cursor->estimatedResultCount);
}
echo getGoogleCount('stackoverflow.com');
?>
good as far as I want to know about the result counts
But the next thing I want is to list all the results on my website. I am unable to grab the results because when we write
$data->responseData->cursor->estimatedResultCount
It goes straight
But when we try to get results. I don't know how to do, just to print the idea
$data->responseData->results->[url & title & content here]
Because here results is an array. and I don't know how can I store info in an array in this case.
Have been searching for a long time but can't find anything related.....
Thanks in advance...
The easiest way is to use:
$data = json_decode($content, true);
That will convert objects to normal associative arrays which are probably easier to handle.
Then you access your values by something like this:
$results = $data['responseData']['results']; //array
$googleCount = $data['responseData']['cursor']['estimatedResultCount'];
Then with the results you can do something like this:
foreach ($results as $result) {
echo $result['title'].' -> '.$result['url'] . '<br />';
}
But of course if you don't like associative arrays and you prefer objects, you could do it also this way:
$data = json_decode($content);
foreach ($data->responseData->results as $result) {
echo $result->title .' -> '.$result->url.'<br />';
}
If you want to check which properties has the $result, just use print_r or var_dump.

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;
...
}

Categories