Accessing JSON array data in PHP - php

I am trying to get some data from an external API. From the JSON data I want to retrieve some data as marked in the image.
I can access the "teams" data by using this code -
foreach( $data->data as $info ) {
echo '<li class="team-1">'. $info->teams[0].'</li>';
echo '<li class="team-2">'. $info->teams[1].'</li>';
};
But when I try to access data more deep from array of objects it doesn't work & gives me error -
foreach( $info->sites as $site) {
foreach( $site->odds as $odd) {
echo $odd->h2h[0];
}
}
So my question is what is the best way to loop through the data to access these arrays. I am using this code in Wordpress but I think it will be same as PHP.

You should access h2h directly from odds, since it's not an array, but an object
foreach( $info->sites as $site) {
echo $site->odds->h2h[0];
}

It looks like odds is an object rather than an array.
If h2h will always be the only property in odds then you can try:
foreach( $info->sites as $site) {
echo $site->odds->h2h[0];
}
Alternatively, if h2h will not always be the only property in odds, then you may want to try casting it into an array:
foreach( $info->sites as $site) {
foreach( (array)$site->odds as $odd) {
echo $odd[0];
}
}

You get this json from an external api and convert it using json_decode, right? If that is so, just use the second parameter "$assoc" and set it to true to not get an object, but an associative array that you can use like this:
$info = json_decode($api_answer,true);
if(isset($info['sites']['odds'])){
foreach($info['sites']['odds'] as $odd){
echo $odd['h2h'][0]
}
}

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.

Access Element in JSON data that doesn't have a standard name

I'm using the Kraken API to get a list of available currency pairings.
Here is the endpoint: https://api.kraken.com/0/public/AssetPairs
$kraken_coins =
file_get_contents('https://api.kraken.com/0/public/AssetPairs');
$kraken_coins = json_decode($kraken_coins, true);
foreach ($kraken_coins['result'] as $coin) {
echo $coin . "<br>";
}
I'm trying to extract the first element inside of "result", however each of these elements are named differently so I'm not sure how to target it. For example, the first two currency pairings returned are "BCHEUR" and "BCHUSD".
So with the loop I have above, it just echos "Array" repeatedly... not what I'm going for.
How do I target that element so I can loop through each one? Thanks!
Since, the json structure is:
You need to use:
foreach ($array as $key => $value) {
}
In this case:
foreach ($kraken_coins['result'] as $coin => $coindata) {
echo $coin . "<br>";
}

PHP function return multiple JSON object

I have a php function that currently looks like this
function renderJson(PageArray $items) {
$myData = array();
$myData['title'] = [];
$myData['url'] = [];
// cycle through all the items
foreach($items as $item) {
array_push($myData["title"],$item->title);
array_push($myData["url"],$item->url);
}
return json_encode($myData);
}
It currently works in this shape as output
{"title":["A","B"],"url":["A","B"]}
But this is what I am trying to achieve
{"title":["A"],"url":["A"]},{"title":["B"],"url":["B"]}
I am trying to return it as a JSON encode.The $item->title and $item->url returns a string.Any help would be great.
So now you get this :
{"title":["A","B"],"url":["A","B"]}
But you want this :
{"title":["A"],"url":["A"]},{"title":["B"],"url":["B"]}
What you want is add a new "item" each time you loop and each item have a title and an url. Right now you return an array that contain 2 sub-array : one for the title, one for the url.
Try this way :
function renderJson(PageArray $items) {
// Your result array
$myData = array();
// cycle through all the items
foreach($items as $item) {
// Each time you loop, you add a new array in your main array with a title and an URL
$myData[] = array(
"title" => $item->title,
"url" => $item->url
);
}
return json_encode($myData);
}
I used [] because he does what you need : push element at the end of your main array. It's the short way to use array_push(). Here is the documentation for more details : http://php.net/manual/en/function.array-push.php
The output will be :
[{"title":["A"],"url":["A"]},{"title":["B"],"url":["B"]}]
What you want to return is not, of course, valid json. At this point return an array containing those two objects (i.e., push the whole $item to $myData)
function renderJson(PageArray $items) {
$myData = array();
// cycle through all the items
foreach($items as $item) {
array_push($myData,['title' => $item->title, 'url' => $item->url]);
}
return json_encode($myData);
}
which gives you something in the form of
[{"title":"A","url":"A"},{"title":"B","url":"B"}]
You create invalid JSON by concatenation your JSON by comma. Either get your client (speak receiver of the json data) to split the result by comma and then parsing each JSON by its own.
Otherwise you could create a "big" JSON string, containing both (or all if there are more) of your JSON data.
Just create an array in PHP, add a new element for each JSON data, then json_encode() it and go over it by a loop in your client.
What you will use in the end, doesnt really matter that much, but I would use the second approach by a lot over the first, since it´s much cleaner.

How do I access certain elements of a PHP multidimensional array?

I have the following multidimensional array.
I have run a foreach loop and am trying to echo the client nicknames of the 2 users. The code I am running is as follows.
$client_r = $Ts3->clientList();
foreach ($client_r as $client)
{
echo $client['data']['client_nickname'];
}
What am I doing wrong?
Try this:
foreach ($client_r as $client)
{
echo $client['data'][0]['client_nickname'];
echo $client['data'][1]['client_nickname'];
// As there are further arrays inside array, so you have to include the index also
}
If you start from the data then your access will be easy-
In data you have again array, so the $client now stores the sub array, now you can easily access your client_nickname.
$client_r = $Ts3->clientList();
foreach ($client_r['data'] as $client){
echo $client['client_nickname'];
}
This may be solve your problem.

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.

Categories