Array json parsing - php

i'm parsing a json file (api rest) but i can't solve a problem. This is the json file.
Array
(
[110197275197292] => Array
(
[mid] => 110197275197292
[home] => FC Den Bosch
[away] => SC Telstar
[country_leagues] => Netherlands - Eerste Divisie
[leagues] => Eerste Divisie
[country] => Netherlands
[score] =>
[home_score] => 0
[away_score] => 0
[periodID] =>
[periodTXT] =>
[periodTime] => 1632923759
[startTime] => 1633111200
[lastUpdateTime] => 1632923357
[minutes] => 0
[status] => 1
[importancy] => 281
[odds] => Array
(
[home] => 2.45
[draw] => 3.70
[away] => 2.40
[1st-1] => 2.90
[1st-0] => 2.35
[1st-2] => 2.87
[2nd-1] => 2.70
[2nd-0] => 2.70
[2nd-2] => 2.65
with this code below i print the value of the array, and work.
foreach ($response as $key1 => $value1){
echo $response[$key1]['home'] .'<br>';
}
Now i would insert the value of the array in a variable, something like that
foreach ($response as $key1 => $value1){
$prova = $response[$key1]['home'];
}
<?php echo $prova; ?>
This way I could recall it in an html table. This code print me only one value of the array and does not loop (foreach). The value that prints in this case is Nashville SC which is a value found in the json file. Where is my mistake? there is a way to encapsulate array values in a variable and then recall it later in the html code?

You are always overwriting the $prova variable with the home team. You should either convert $prova to an array and work with it or move the echo inside your loop to print everything.
Moreover you should use more distinct names to your variables so both we and you understand your code.
//1. echo way
foreach ($response as $matchDate => $matchData){
$prova = $matchData['home'];
echo $prova;
}
//2. array way
$prova = [];
foreach ($response as $matchDate => $matchData){
$prova[$matchDate] = $matchData['home'];
}
var_dump($prova); //This will print the whole array of home teams.

Related

Get Array value based on object ids with php

I have this Array but i don't know how to get the [discount_amount] based on the [object_ids].
For example i would like to get the 93 value if my [object_ids] contain 81.
Array
(
[0] => Array
(
[id] => rule_5b0d40cd1408a
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 81
)
[discount_type] => amount
[discount_amount] => 93
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
[1] => Array
(
[id] => rule_5b0d4e0f3b0b4
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 110
)
[discount_type] => amount
[discount_amount] => 50
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
)
You could use a foreach and use in_array to check if the array object_ids contains 81.
foreach ($arrays as $array) {
if (in_array(81, $array["object_ids"])) {
echo $array["discount_amount"];
}
}
Demo
Try with this code .
Assuming $dataArray is the array you have printed.
foreach ($dataArray as $key => $value){
if($value['object_ids'][0] == 83){
$discount_amount = $value['discount_amount'];
}
}
echo $discount_amount
The way I mostly do this is as followed:
# Save retrieved data in array if you want to.
$test = array();
foreach($array as $line){
# Count the row where discount_amount is found.
$test[] = $line['9'];
echo "Result: ".$line['9']. "<br \>\n";
# OR another method is
$test[] = $line['discount_amount'];
echo "Result: ".$line['discount_amount']. "<br \>\n";
}

Converting a JSON Output into a HTML Table

So I have a JSON output here https://squad-servers.com/api/?object=servers&element=detail&key=fupxq9hl1vkxb4yxhkggada7e0jz8p6w1
What I'd like to do is get this into a HTML Table to create my own status page as such, this is where I got with it.
<?php
$json=file_get_contents("https://squad-servers.com/api/?object=servers&element=detail&key=fupxq9hl1vkxb4yxhkggada7e0jz8p6w1");
$data = json_decode($json);
print_r($data);
?>
stdClass Object
(
[id] => 2272
[name] => [ZXD] Zulu X-Ray Delta EU/UK #2
[address] => 164.132.202.16
[port] => 7797
[private] => 0
[password] => 0
[query_port] => 27175
[location] => United Kingdom
[hostname] => Zulu X-Ray Delta EU/UK #2
[map] => Kokan AAS v1
[is_online] => 0
[players] => 0
[maxplayers] => 72
[version] => a-8.8.116.11628
[platform] => windows
[uptime] => 97
[score] => 4
[rank] => 81
[votes] => 0
[favorited] => 0
[comments] => 0
[url] => https://squad-servers.com/server/2272/
[last_check] => December 7th, 2016 08:50 AM EST
[last_online] => December 7th, 2016 07:25 AM EST
)
But how can I get this into a table, so I can echo / print out each part of the array?
Many thanks,
$tbl = "<table><tr><th>".implode('</th><th>',array_keys((array)$data))."</th></tr>";
$tbl .= "<tr><td>".implode('</td><td>',(array)$data)."</td></tr></table>";
print $tbl;
...on way to rome.
$head=array();
$body=array();
foreach($data as $k=>$v){
$head[]="<th>$k</th>";
$body[]="<td>$v</td>";
}
print "<table><tr>".implode('',$head)."</tr><tr>".implode('',$body)."</tr></table>";
...another way.
(every used function can be found at php.net)
This will only work on your example. Not every json output can be easy printed into an html-table.
You can print each value using foreach:
foreach ($data as $key => $value) {
echo $value;
}
http://php.net/manual/en/control-structures.foreach.php
All you need is to call print_r($data->name); so echo $data->name with current api call.
if you have more than one result:
<table>
<?php foreach ($object as $value) {
echo '<tr>';
echo '<td>'.$value->name.'</td>';
echo '<td>'.$value->address.'</td>';
echo '<td>'.$value->hostname.'</td>';
echo '<td>'.$value->uptime.'</td>';
echo '</tr>';
}
}
?>
</table>
json_decode has an optional second parameter determining whether you want to have an associated array. This parameter is false by default and therefore you get a standard object, which is much more difficult to handle. Instead, make sure that you have an associated array:
$data = json_decode($json, true);
foreach ($data as $key => $value) {
//Do something with $key and $value
}

Nested Arrays PHP

Im struggling with displaying the country_name, country_prefix followed by the city_name and city_prefix to display in PHP
Array (
[0] => stdClass Object
(
[country_name] => Russian Federation
[country_prefix] => 7
[country_iso] => RU
[cities] => Array
(
[0] => stdClass Object
(
[city_id] => 107
[city_name] => Moscow
[city_prefix] => 495
[city_nxx_prefix] =>
[setup] => 0
[monthly] => 60.9
[isavailable] => 1
[islnrrequired] => 0
)
...
This above returns the $results array and Im currently using something like this but have tried many iterations.
echo '<br />Results: <br />';
foreach($result as $countries => $country) {
foreach($country as $details => $value) {
echo $value . "<br/>";
}
}
Try this:
foreach($results as $country){
// country name in $country->country_name
foreach($country->cities as $city){
echo $city->city_name.'<br/>';
}
}
As you've been told in comments, you have an array of objects. You can iterate it with foreach, but then you should access its properties using the proper syntax (->)

PHP get array value from json

Using PHP, how would I access the inner array values, specific to this example the values specific to each game array, from a json feed similar to this:
Array
(
[startIndex] => 3
[refreshInterval] => 60
[games] => Array
(
[0] => Array
(
[id] => 2013020004
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] => final
)
[1] => Array
(
[id] => 2013020005
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] =>
)
I have tried nesting a foreach loop inside a foreach loop similar to this:
foreach ($json as $key => $jsons) {
foreach ($jsons as $my => $value) {
echo $value;
}
}
If that is an array you are looking at then you can reach the values
foreach($json["games"] as $game) {
foreach ($game as $key => $value) {
echo $value;
}
}
This should give you the values within each array in the games section.
EDIT: to answer additional question in comment
To get the specific values of the game like the id, the second foreach loop will not be needed. Instead do the following:
foreach($json["games"] as $game) {
echo $game['id'];
}
You just access it as an associative array.
$json['games'][0]['id'] // This is 2013020004
$json['games'][1]['id'] // This is 2013020005
You can loop through the games like so:
foreach($json['games'] as $game){
print_r($game);
}
If you are trying to access this,
[0] => Array
(
[id] => 2013020004
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] => final
)
[1] => Array
(
[id] => 2013020005
[gs] => 5
[ts] => WEDNESDAY 10/2
[tsc] => final
[bs] => FINAL
[bsc] =>
)
..then you are doing it right. The only problem is you are trying to echo an array. Trying using print_r($value). If you want a specific value, like the id. You can echo $value['id'];
I think you could use one of the many example of recursive array_key_search. This way you could simply do :
$firstGame = array_search_key(0, $array);
$firstGameId = $firstGame["id"];

PHP invalid argument supplied in foreach

I am trying to read out this nested array with a foreach loop but get an error "invalid argument supplied in foreach"
Array (
[regenerated] => 1302668837
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[cart_contents] => Array (
[c4ca4238a0b923820dcc509a6f75849b] => Array (
[rowid] => c4ca4238a0b923820dcc509a6f75849b
[id] => 1
[qty] => 1
[price] => 29.95
[name] => Training DVD
[optione] =>
[subtotal] => 29.95
)
[c81e728d9d4c2f636f067f89cc14862c] => Array (
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[subtotal] => 1200
)
[total_items] => 2
[cart_total] => 1229.95
)
[johndoe] => audio
[totalItems] => 2
)
$cart_contentz = $_SESSION['cart_contents'];
foreach($cart_contentz as $itemz => $valuez) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
the first level of your main array has items that are sub-arrays and some that are not. Your second loop doesn't work on non-array items.
Thus, your code should be:
foreach($cart_contentz as $itemz => $valuez) {
if (is_array($valuez)) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
} else {
echo "$itemz: $valuez<br>";
}
}
you'll need to load that array into your $_SESSOIN['cart_contents'] which may have been done. secondly, your inner foreach is acting on the values of that array which are not arrays. I'm fairly certain that the inner foreach is causing your woes. Also, your Array may just be for illustrating what's in $_SESSION['cart_contents'], but adding quotation marks instead of square brackets around the keys will make it more uniform and easier to read.
Update:
after seeing the reformatted code, thanks #AgentConundrum, now I can more clearly see the issue. Try adding an if(is_array($valuez)) around your inner foreach.
Maybe to use recursion:
function printArray($array, $parent=false, $level=0) {
if (!($parent === false)) echo "<b>".str_pad('',($level-1)*4,"-")."[$parent] =></b><br />\n";
foreach ($array as $key=>$value) {
if (!is_array($value)) echo str_pad('',$level*4,"-")."[$key] => $value<br />\n";
else printArray($value, $key, $level+1);
}
}
print_array($your_array);

Categories