How do you use a JSON API in PHP on Wordpress? - php

Here my url address for https://goalserve.com/getfeed/mytoken/topscorers/1204?json=1
How can I get the "player" data, I want to use make "top scorers standing widget" on my PHP Wordpress site.
{
"?xml":{
"#version":"1.0",
"#encoding":"utf-8"
},
"topscorers":{
"#sport":"soccer",
"tournament":{
"#name":"Premier League",
"#stage_id":"12041081",
"#gid":"1204",
"#is_current":"True",
"#id":"1204",
"player":[
{
"#pos":"1",
"#name":"Mohamed Salah",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"15",
"#penalty_goals":"2",
"#id":"138653"
},
{
"#pos":"2",
"#name":"Diogo Jota",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"10",
"#penalty_goals":"0",
"#id":"374031"
},
{
"#pos":"3",
"#name":"J. Vardy",
"#team":"Leicester City",
"#team_id":"9240",
"#goals":"9",
"#penalty_goals":"0",
"#id":"159732"
}
]
}
}
}

Answer
https://www.php.net/manual/en/function.json-decode.php
To do this you must first decode the json string into a php object. Then you must drill down to the proper data that you want. You can do this with the -> operator like so:
$players = json_decode($raw_string)->{'topscorers'}->{'tournament'}->{'player'};
Note that you should save the result of the decoded json string if you plan on reusing the data. Don't decode it more than once.
After you have the players, you can then iterate over the data and do what you want with it. Here is a minimal example with your data so you can see it all working together.
Example
Dataset
<?php
$raw_string = '
{
"?xml":{
"#version":"1.0",
"#encoding":"utf-8"
},
"topscorers":{
"#sport":"soccer",
"tournament":{
"#name":"Premier League",
"#stage_id":"12041081",
"#gid":"1204",
"#is_current":"True",
"#id":"1204",
"player":[
{
"#pos":"1",
"#name":"Mohamed Salah",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"15",
"#penalty_goals":"2",
"#id":"138653"
},
{
"#pos":"2",
"#name":"Diogo Jota",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"10",
"#penalty_goals":"0",
"#id":"374031"
},
{
"#pos":"3",
"#name":"J. Vardy",
"#team":"Leicester City",
"#team_id":"9240",
"#goals":"9",
"#penalty_goals":"0",
"#id":"159732"
}
]
}
}
}';
?>
Processing
<?php
$php_object = json_decode($raw_string);
$players = $php_object->{'topscorers'}->{'tournament'}->{'player'};
$html = '';
$html .= '<table>';
$html .= '<tr>';
$html .= '<td>Pos</td>';
$html .= '<td>Player</td>';
$html .= '<td>Team</td>';
$html .= '<td>Goals</td>';
$html .= '</tr>';
foreach ($players as $p) {
$html .= '<tr>';
$html .= '<td>' . $p->{'#pos'} . '</td>';
$html .= '<td>' . $p->{'#name'} . '</td>';
$html .= '<td>' . $p->{'#team'} . '</td>';
$html .= '<td>' . $p->{'#goals'} . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo($html);
?>
Output
<table><tr><td>Pos</td><td>Player</td><td>Team</td><td>Goals</td></tr><tr><td>1</td><td>Mohamed Salah</td><td>Liverpool</td><td>15</td></tr><tr><td>2</td><td>Diogo Jota</td><td>Liverpool</td><td>10</td></tr><tr><td>3</td><td>J. Vardy</td><td>Leicester City</td><td>9</td></tr></table>
Pos
Player
Team
Goals
1
Mohamed Salah
Liverpool
15
2
Diogo Jota
Liverpool
10
3
J. Vardy
Leicester City
9

Related

How to rowspan a td if it has a duplicate value

I am trying to manipulate my table using rowspan but I'm kinda struggling.
My expected output should be if there's two duplicated names I want it to have a rowspan in the table. But my problem occurs if there's a third duplicate and its separated between another name (in this case 'ruby' is in between) my table will have an excess column.
My code is kinda like this
sample:
$gems = array(
0 => array:2[
name: Amber
value: 20
]
1 => array:2[
name: Amber
value: 30
]
2 => array:2[
name: Ruby
value: 40
]
3 => array:2[
name: Amber
value: 50
]
4 => array:2[
name: Emerald
value: 60
]
);
This is how I map the rowspan
$rows = array();
foreach($rows as $key => $gem){
$rows[$key] = $gem['name'];
}
$arr = array_replace($row,array_fill_keys(array_keys($row, null),''));
$rowspan = array_count_values($ar);
$rowspan output will be this which i use on the table.
array:3(
"Amber" => 3
"Ruby" => 1
"Emerald" => 1
)
Then my display is kinda like this (not exact). Im injecting the rowpan on $rowspanDuplicated
$html = '<table>'
foreach($gems as $key => $gem){
$html .= '<tr>'
$rowspanDuplicated = 'rowspan="'. $rowspan[$gem['name']].'"';
if($rowspan[$gem['name']] <= 1){
$rowcount = 1;
$html .= '<td>' . $this->n($sv['name']). ' </td>'
} else {
if($rowcount<=1){
$html .= '<td' . $rowspanDuplicated . '>' .$this->n($sv['name']) . '</td>';
}
if($rowspan[$sv['name']] == $rowcount){
$rowcount=1;
} else {
$rowcount++;
}
}
$html .= '<td>' . $this->n($sv['value']). ' </td>'
$html .= '</tr>'
}
$html = '</table>'
The problem to this code is that $gem[3] will also have a rowspan
I want my table something like this.
_________________
Amber | 20
|-----
| 30
________|________
Ruby | 40
_________________
Amber | 50
________|________
Emerald | 60
_________________
I think you should group your array based on name in the first place.
public function group($gems)
{
$grouppedGems = [];
foreach($gems as $gem) {
if (!array_key_exists($gem['name'], $grouppedGems))
$grouppedGems[$gem['name']] = [];
$grouppedGems[$gem['name']][] = $gem;
}
return $grouppedGems;
}
$html = '<table>'
foreach($gems as $name => $gem){
$html .= '<tr><td rowspan="' . count($gem) . '">' . $name . '</td><td>';
foreach($gem as $item) {
$html .="<tr><td>{$this->n($item['value'])}</td></tr>";
}
$html .= '</td></tr>';
}
$html = '</table>';
I didn't test the html string, but I think it will work. BTW, you won't need rowspan, bu I added it just in case.
blade version
#foreach($gems as $gem)
<tr>
<td
#if(!$loop->last && $gems[$loop->index+1]->gem['name'] == $gem['name']) rowspan=2 >{{$gem['name']}}</td>
<td>{{$gem['value']</td>
<tr>
#endforeach

Putting php arrays into html tags

I am trying to make a table that has different colors for each of its columns. There will be four columns.
$colors = array("background-color:red;", "background-color:gold", "background-color:pink;", "background-color:purple;");
$html = '<table>';
foreach( $array as $key=>$value){
$html .= '<tr style="background-color:white;">';
foreach($value as $key2=>$value2){
$html .= '<td>' . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}
I created an array called colors that has the strings of the colors I want, but I don't know how to put that into the tag. I tried typing it in there, but since it is a string, it takes it as text instead of as code. Where it says "background-color:white;", I'd like it to call the values from the array instead. Thanks.
You can array_pop for this provided you have exactly 4 columns. You also can't apply background colours to <tr> like that, you need to apply them to the <td>
$colors = array("background-color:red;", "background-color:gold", "background-color:pink;", "background-color:purple;");
$html = '<table>';
foreach( $array as $key=>$value){
$color = array_pop($colors);
$html .= "<tr>";
foreach($value as $key2=>$value2){
$html .= "<td style='{$color}'>" . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}

PHP foreach $output variation?

I need a little help on getting a rule in to output something else if a certain variable is called.
To break it down I have the following listed:
private $zebra_moto_symbol = array
( "ES400", "MC9500", "MC9200", "MC9190", "MC9094", "MC9090", "MC9097", "MC9060",;
and using this code it pulls the models into the page in a list:
public function manufacturer_models_list() {
$manu_name = $this->manufacturer_name;
$output = "<ul>";
sort($this->$manu_name);
foreach($this->$manu_name as $model) {
$output .= "<li>" . "" . $model . "</li>";
}
$output .= "</ul>";
$output .= "<p class=\"clear\"></p>";
$output .= "Arrange A Repair";
return $output;
}
On all but two of these, I need it display the repair.php link, however on two these need to be different. What would I need to input to make this happen?
Thanks in advance (sorry, this one stumped me).
:)
You can use a switch statement for this.
<?
public function manufacturer_models_list() {
$manu_name = $this->manufacturer_name;
$output = "<ul>";
sort($this->$manu_name);
foreach ($this->$manu_name as $model) {
switch($model) {
//Output NOT repair.php on this list of strings
case "ES400":
case "MC9500":
$output .= "<li>DIFFERENT OUTPUT</a></li>";
break;
//default is the action that happens if none of the previous conditions are met
default:
$output .= "<li>" . "" . $model . "</li>";
break;
}
}
$output .= "</ul>";
$output .= "<p class=\"clear\"></p>";
$output .= "Arrange A Repair";
return $output;
}
?>
Read more about Switch Statements
If I understood correctly, what you want is to have a different output on certain values.
I would think about have another array to hold the values that you want a different output and you can do something like this:
$different_output_array = ['ES400', 'MC9500']; # you can add new elements any time
and just modify your function to something like this:
public function manufacturer_models_list() {
$manu_name = $this->manufacturer_name;
$output = "<ul>";
sort($this->$manu_name);
foreach($this->$manu_name as $model) {
if(in_array($model,$different_output_array))
{
$output .= "<li>" . "" . $model . "</li>";
}
else
{
$output .= "<li>" . "" . $model . "</li>";
}
}
$output .= "</ul>";
$output .= "<p class=\"clear\"></p>";
$output .= "Arrange A Repair";
return $output;
}
Hope this can help.

JSON encode to create a table

How can I eventually put the following code into a table or viewable format.
$query =
"SELECT title, descr FROM details";
$result = mysqli_query($connection,$query);
$details = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($details, $row);
}
echo json_encode($details);
No need to json encode the result, however with making tables I like to make a json template file to dictate how the table should be constructed so that I can make changes easily.
// this would normally be located elsewhere.
$templateJson = '"columns": {
"title":{
"title": "Title",
"class": "title"
},
"descr":{
"title": "Description",
"class": "descr"
}
}';
$template = json_decode($templateJson);
if(is_array($details))
{
$markup = "<table><thead><tr>";
foreach($template["columns"] as $col=>$format)
{
$markup .= '<th class="'.$format['class'].'">';
$markup .= $format['title'];
$markup .= '</th>';
}
$markup .= "</tr></thead><tbody>";
foreach($details as $i=>$row)
{
$markup .= '<tr>';
foreach($template as $col=>$format)
{
$markup .= '<td>'.$row[$col].'</td>';
}
$markup .= '</tr>';
}
$markup .= "</tbody></table>";
}
echo $markup;
I tend to do way more loops than I probably should though, there may be a more optimal way but this will give you valid table markup.

PHP While Loop/Foreach Loops

I have a question on a different way to wright this code because its not doing what I want it to do..
I am creating a forum list that will display the section under that category. Well this is the issue as you can see that I have an If () {}Else {} statement that is being used to put the information in that list I want. The problem is that I need to add a special class to the last section under that category that will be called last-tr. Now my issue that I have is all the information is making it to the screen but the class is only applied to the last row and now the last row of all the category's which is what i'm looking for.
So something like this,
Welcome Center
Introduce Yourself
Say Hello To our Admins (last-tr)
Game
COD
BF4 (last-tr)
Code
PHP
Java
PDO (last-tr)
but what my code is giving me is
Welcome Center
Introduce Yourself
Say Hello To our Admins
Game
COD
BF4
Code
PHP
Java
PDO (last-tr) <- Just that one.
Here is the code
<?php
include '../../core/init.php';
include '../../includes/head.php';
//Getting Categories under Welcome
$db = DB::getInstance();
$user = New User();
$forum = New Forum();
$list = '';
$category = $db->query('SELECT * FROM forum_categories');
foreach ($category->results() as $category) {
$list .= '<thead>';
$list .= '<tr>';
$list .= '<th class="titles">' . $category->title . '</th>';
$list .= '<th>Last Post</th>';
$list .= '<th>Topics</th>';
$list .= '<th>Replies</th>';
$list .= '</tr>';
$list .= '</thead>';
$list .= '<tbody>';
$sections = $db->query("SELECT * FROM forum_section WHERE category_id = '$category->id'");
foreach ($sections->results() as $section) {
$x = 0;
if ($x < $sections->count()) {
$list .= '<tr>';
$list .= '<td>';
$list .= '<a href="/category.php?id='. $section->id .'">';
$list .= '<img scr="/images/icons/iconmonstr/intro.png">';
$list .= '</a>';
$list .= '' . $section->title . '';
$list .= '<span>' . $section->desc . '</span>';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
$x++;
}else {
$list .= '<tr class="last-tr">';
$list .= '<td>';
$list .= '' . $section->title . '';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
}
}
$list .= '</tbody>';
}
?>
<link rel="stylesheet" href="/css/fourms.css">
<title>Forums</title>
</head>
<body>
<?php include '../../includes/header.php'; ?>
<section id="main_section">
<section id="main_content">
<div id="forum-section">
<table class="forumlist">
<?php echo $list; ?>
</table>
</div>
</section>
</section>
<?php include('../../includes/footer.php'); ?>
Your if-statement should be if ($x < $sections->count()-1) because the last index of an array is always count-1 due to starting at 0.
OR
You could also fix it here by starting $x at 1, since you are using a foreach with the counter on the side, so its not like you'll get an out of index error. In other words:
foreach ($sections->results() as $section) {
$x = 1;
if ($x < $sections->count()) {
...
$x++;
}else {
...
}
}
But going with the first option is probably more straight-forward.
You are testing against your overall class not the data within the class.
$sections->count() is counting all of the sections not the entries in teh one section you are dealing with.
You need to test the count of the singular section
So if you had
$sectionsAll = array(
sectionOne = array( 1, 2, 3),
sectionTwo = array( 1, 2, 3),
sectionThree = array( 1, 2, 3)
);
You are currently testing on $sectionsAll, you need to check against sectionOne, sectionTwo, sectionThree

Categories