JSON encode to create a table - php

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.

Related

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

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

Get Parent Value and Combine To Child Value Using Loop

i have data and want to modify the result using parent and child method. As an example below.
I try with following code but have no luck because the last iteration give wrong result as seen on screenshot below, Is there any idea how to solve it?? live code here https://paiza.io/projects/vS4BHo0mMrKiJZoPpMoNvQ
<?php
$data = array("022.04.GA", "4660", "4660.CBD", "4660.CBD.002", "52", "A", "533111", "022.04.WA", "4631", "4631.EAF", "4631.EAF.001", "51", "B", "524111", "524113", "52", "C", "521211", "524113", "4631.EAH", "4631.EAH.001", "51", "B", "521211", "522131", "4634", "4634.EAG", "4634.EAG.001", "51", "C", "521219", "522191");
echo "<table>";
echo "<tr>";
echo "<td>Code</td><td>Result</td>";
foreach($data as $item)
{
$length = strlen($item);
$data = '';
if($length==9) {
$value = $item;
} elseif($length==4) {
$value .= $data.'.'.$item;
} elseif($length==8) {
$output = substr($item,-4);
$value .= $data.$output;
} elseif($length==12) {
$output = substr($item,-4);
$value .= $data.$output;
} elseif($length==3) {
$value .= $data.'.'.$item;
} elseif($length==1 or $length==2) {
$value .= $data.'.'.$item;
} else {
$value .= $data.'.'.$item;
}
echo "<tr>";
echo "<td>$item</td>";
echo "<td>$value</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
?>

Google Analytics API v3 how to extract values?

I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;
$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working

PHP odd string-related performance issue

I have a class that is building some HTML using data stored in an array. There are around 100 items in this array. Each item includes information like company name, a description, and flags for the different programming languages the company supports. I am doing string concatenation as I build the HTML for each item.
I have noticed that performance suddenly takes a huge hit when I append the programming language data. I see the page rendering timer jump from 0.15 secs to ~0.60 secs. This time includes grabbing the same data from the database each time. I can consistently get the performance to jump between these 2 times but commenting/uncommenting the following line of code:
$html .= '<div class="programmingLanguages"><strong>Programming Languages</strong> '.implode(', ', $progLanguagesArray).'</div>';
I've also been able to get the same performance drop by appending a long test string, something like this:
$html .= 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest';
What's especially bizarre is that I have another line of code that uses the same 'implode' function and does NOT make any significant difference in performance:
$html .= '<div class="integrationMethods"><strong>Integration Methods:</strong> '.implode(', ', $intMethodsArray).'</div>';
Does anybody have any insight into what might be going on here? I am doing tons of concatenation like this elsewhere in my code and haven't seen anything like this before. At this point, I'm stumped.
Here's the full class:
class DeveloperView {
public static function getHtml($developers) {
$html = '';
$html .= '<div>';
$html .= '<div>';
$count = 0;
foreach ($developers as $developer) {
$url = $developer['attributes']['url'];
$phone = $developer['attributes']['phone'];
$company = $developer['attributes']['desc'];
$active = $developer['attributes']['active'];
$desc = $developer['object_value'];
$intMethodsArray = array();
if ($developer['attributes']['m1']) { $intMethodsArray[] = 'method 1'; }
if ($developer['attributes']['m2']) { $intMethodsArray[] = 'method 2'; }
if ($developer['attributes']['m3']) { $intMethodsArray[] = 'method 3'; }
if ($developer['attributes']['m4']) { $intMethodsArray[] = 'method 4'; }
if ($developer['attributes']['m5']) { $intMethodsArray[] = 'method 5'; }
$progLanguagesArray = array();
if ($developer['attributes']['dotnet']) { $progLanguagesArray[] = '.Net (C# or VB.Net)'; }
if ($developer['attributes']['asp']) { $progLanguagesArray[] = 'Classic ASP'; }
if ($developer['attributes']['cf']) { $progLanguagesArray[] = 'Cold Fusion'; }
if ($developer['attributes']['java']) { $progLanguagesArray[] = 'Java'; }
if ($developer['attributes']['php']) { $progLanguagesArray[] = 'PHP'; }
if ($developer['attributes']['perl']) { $progLanguagesArray[] = 'Perl'; }
if ($developer['attributes']['other']) { $progLanguagesArray[] = 'Other'; }
$html .= '<div class="';
if ($count % 2 == 0) {
$html .= 'listingalt';
} else {
$html .= 'listing';
}
$html .= '">';
$html .= '<div class="developerPhone">'.$phone.'</div>';
$html .= '<a class="ext_link" target="_blank" href="'.$url.'">'.$company.'</a>';
$html .= '<div>';
if (!empty($intMethodsArray)) {
$html .= '<div class="integrationMethods"><strong>Integration Methods:</strong> '.implode(', ', $intMethodsArray).'</div>';
}
if (!empty($progLanguagesArray)) {
$html .= '<div class="programmingLanguages"><strong>Programming Languages</strong> '.implode(', ', $progLanguagesArray).'</div>';
}
$html .= '</div>';
$html .= '<p>'.$desc.'</p>';
$html .= '</div>'."\n";
$count++;
}
$html .= '</div></div>';
return $html;
}
}
Now that I can provide an answer, I'll just post my follow-up comment as the 'answer'...
I did indeed have a 'bug' in my timer, in that it was calculating the end processing time AFTER the echo of the HTML. So the amount of data being sent to the browser was effecting the processing time, where I was expecting to see the time spent processing BEFORE transmitting any data.

output query in strict table formate in code-igniter

my code is below.it show the output in table format having no problems.
But when the particular tr gets long output from database then the table break.
Now how can i fixed the tr width strictly?let say i want each td cannot be more than 100px.
How can i do it?
Note: Here table means html table,not the database table.
if ($query->num_rows() > 0)
{
$output = '';
foreach ($query->result() as $function_info)
{
if ($description)
{
$output .= ''.$function_info->songName.'';
$output .= ''.$function_info->albumName.'';
$output .= ''.$function_info->artistName.'';
$output .= ''.$function_info->Code1.'';
$output .= ''.$function_info->Code2.'';
$output .= ''.$function_info->Code3.'';
$output .= ''.$function_info->Code4.'';
$output .= ''.$function_info->Code5.'';
}
else
{
$output .= ''.$function_info->songName.'';
}
}
$output .= '';
return $output;
}
else
{
return 'Result not found.';
}
thanks
riad
You can either do it in the HTML...
<td style="width: 100px">
Or you can try using wordwrap.

Categories