How to show json data with column name in php - php

i have some JSON data
i am able to retrieve data out of it but i want data to be displayed with columns
this the JSON
{"ObjectId":43,"ObjectName":"MEGA MELA","ObjectTitle":"Event Created by API","ObjectDescription":"NEW EVENT BY API","ObjectLabel":"","ObjectTypeId":33,"MaxFieldsExpected":5,"ObjectValueType":null,"ObjectControlType":"","IsDeleted":true,"CreatedDate":"2019-05-22T07:56:03.767","CreatedBy":null,"EditedDate":null,"EditedBy":null,"DeletedDate":null},{"ObjectId":44,"ObjectName":"Event x11","ObjectTitle":"Event Created by API","ObjectDescription":"NEW EVENT BY API","ObjectLabel":"","ObjectTypeId":33,"MaxFieldsExpected":5,"ObjectValueType":null,"ObjectControlType":"","IsDeleted":true,"CreatedDate":"2019-05-23T00:33:50.7","CreatedBy":null,"EditedDate":null,"EditedBy":null,"DeletedDate":null}]}
here is what i am doing right now
$jsonData = json_decode($data, TRUE);
foreach ($jsonData as $d) {
foreach ($d as $ins) {
echo "<h3>".$ins['ObjectName']."</h3>";
echo "<h3>".$ins['ObjectDescription']."</h3>";
}
}
OutPut:
MEGA MELA
NEW EVENT BY API
Event x11
NEW EVENT BY API
i want it in this format
ObjectId | ObjectName | ObjectTitle | ObjectDescription | ObjectLabel | ObjectTypeId | MaxFieldsExpected | ObjectValueType | ObjectControlType | IsDeleted | CreatedDate | CreatedBy | EditedDate | EditedBy
43 | MEGA MELA | Event Created by API | NEW EVENT BY API | ..............................................................................
above i am getting data with help of array key now i want extracting keys from JSON like ObjectId or ObjectName making them header of table and showing all the data in columns

on the above example, you can use the key to print the filed name and value will be the data.
here we can loop the field names first to create the heading
I am using table here.
<table>
<?php foreach ($d as $ins) { ?>
//printing field heads
<tr>
<?php
foreach ($ins as $key=>$value) {
echo "<td><h3>".$key."</h3></td>";
} ?>
</tr>
//printing value row
<tr>
<?php
foreach ($ins as $key=>$value) {
echo "<td><h3>".$value."</h3></td>";
} ?>
</tr>
} ?>
</table>

Used an old gist for array2table from here : http://www.aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/
<?php
function array2table($array, $recursive = false, $null = ' ')
{
// Sanity check
if (empty($array) || !is_array($array)) {
return false;
}
if (!isset($array[0]) || !is_array($array[0])) {
$array = array($array);
}
// Start the table
$table = "<table>\n";
// The header
$table .= "\t<tr>";
// Take the keys from the first row as the headings
foreach (array_keys($array[0]) as $heading) {
$table .= '<th>' . $heading . '</th>';
}
$table .= "</tr>\n";
// The body
foreach ($array as $row) {
$table .= "\t<tr>" ;
foreach ($row as $cell) {
$table .= '<td>';
// Cast objects
if (is_object($cell)) { $cell = (array) $cell; }
if ($recursive === true && is_array($cell) && !empty($cell)) {
// Recursive mode
$table .= "\n" . array2table($cell, true, true) . "\n";
} else {
$table .= (strlen($cell) > 0) ?
htmlspecialchars((string) $cell) :
$null;
}
$table .= '</td>';
}
$table .= "</tr>\n";
}
$table .= '</table>';
return $table;
}
$data ='[{"ObjectId":43,"ObjectName":"MEGA MELA","ObjectTitle":"Event Created by API","ObjectDescription":"NEW EVENT BY API","ObjectLabel":"","ObjectTypeId":33,"MaxFieldsExpected":5,"ObjectValueType":null,"ObjectControlType":"","IsDeleted":true,"CreatedDate":"2019-05-22T07:56:03.767","CreatedBy":null,"EditedDate":null,"EditedBy":null,"DeletedDate":null},{"ObjectId":44,"ObjectName":"Event x11","ObjectTitle":"Event Created by API","ObjectDescription":"NEW EVENT BY API","ObjectLabel":"","ObjectTypeId":33,"MaxFieldsExpected":5,"ObjectValueType":null,"ObjectControlType":"","IsDeleted":true,"CreatedDate":"2019-05-23T00:33:50.7","CreatedBy":null,"EditedDate":null,"EditedBy":null,"DeletedDate":null}]';
$jsonData = json_decode($data, TRUE);
echo array2table($jsonData);
?>
DEMO: https://3v4l.org/0n27Y

Second foreach should look like: foreach ($d as $key => $ins) then at $key variable you get your indexes.

Related

PHP code to separate Table based on column values

I have a csv file that should be converted to HTML table based on column values , and I have to put the values into separate table based on first column of csv . And I think the problem is because of '\n' in first column.
So its like this:
Here in Result column, in one row I have three values separated using comma (W,M,P). In the code I wrote it is considered as separate table headers .
Can anyone please help me with this?
This is my code:
<?php
$csv="FinalResult.csv" ;
$csvcontents=file_get_contents($csv);
$csv_array = explode("\n", $csvcontents);
$tables = [];
foreach($csv_array as $key => $value) {
if ($key == 0) {
continue;
}
$line = explode(',', $value);
if (array_key_exists($line[0], $tables)) {
$tables[$line[0]][] = $line;
} else {
$tables[$line[0]] = [$line];
}
}
foreach ($tables as $key => $value) {
echo '<h1> ' .$key. ' </h1>'; // YOUR TITLE (Team)
echo "<table>";
echo '<tr>';
foreach (explode(',', $csv_array[0]) as $keyHeader => $valueHeader) {
if (in_array($keyHeader, [0, 1])) {
continue;
}
echo "<th>$valueHeader</th>";
}
echo '</tr>';
foreach ($value as $keyRow => $valueRow) {
echo '<tr>';
foreach ($valueRow as $keyValue => $valueValue) {
if (in_array($keyValue, [0, 1])) {
continue;
}
echo "<td>$valueValue</td>";
}
echo '</tr>';
}
echo '</table>';
}
?>
I refereed in stack overflow , but there they were giving only single values to a column and not providing multiple values .
But am getting output like this ,
so it takes the value of Result column after '-' as a new heading , i tried but am not able to solve this , can anyone really help me in this matter .
Here is how my output should look like:
I marked in yellow where all the data am getting in same column
This is my csv file :
Team,Date,Opponent,Result
MIN,May-03,UTA,a.b.c=d-e.f-g.h=log4j2-i.xml-j -k -a4j.k=tp_r-RR.xml -
MIN,May-04,SEA,"L,Q,J"
SAC,May-03,DAL,L
SAC,May-04,TOR,W
NYN,May-05,BAL,L
NYN,May-07,MIA,W
Here is the code
<table>
<?php
$csvValues= array_map('str_getcsv', file('FinalResult.csv'));
$counter = 0;
// Header
echo "<tr>";
foreach($csvValues[0] as $headers){
echo "<th>".$headers."</th>";
}
echo "</tr>";
// Content
foreach($csvValues as $values){
echo "<tr>";
if($counter >0){
foreach($values as $data){
echo "<td>".$data."</td>";
}
}
echo "</tr>";
$counter++;
}
?>
</table>

Pass selected option value to mysql query

I have an html select that is filled with data from the database.
It looks like this
echo '<select name="client_list">';
foreach ($htmlselect as $key => $row) {
echo
'<option value='.$row->CUSTOMERCODE.'>'
.$row->CUSTOMERNAME. '</option>';
}
echo '</select>';
Below it I have a table that is populated with values from the DB.
$table = $wpdb->get_results('SELECT STRING, DATE, STRING02 FROM `CUSTOMERFILE` WHERE `code` = 2 AND `status` = 2');
echo '<thead ><tr >';
foreach ($header as $list) {
echo '<th >' . $list . '</th>';
}
echo "<thead></tr>";
if ( !empty( $table) ) {
foreach ( $table as $key => $value ) {
echo '<tr >';
foreach ( $value as $a ) {
if (empty($a)) {
# code...
echo '<td>NULL</td>';
} else {
echo '<td>' . $a . '</td>';
}
}
echo '</tr>';
}
}
Now in this query I want to add to the where another condition that takes the selected option value from the html select
It would look something like this
$table = $wpdb->get_results('SELECT STRING, DATE, STRING02 FROM `CUSTOMERFILE` WHERE `code` = 2 AND `status` = 2 **AND STRING05 = selected option value**');
How do I pass the selected value in the query?
The $wpdb->get_results() function take 2 parameters, the first is the query and the second is the output
$wpdb->get_results($command, $output);

populate php table different fields and headers

Need some help as I have very basic knowledge of code and not sure I understand what i need to.
I have been given two sets of codes from a wordpress plugin support that they say will help me do what I need to do
My goal is to have a table that display different data and headers based on a field called attendee form (each attendee form has different fields).
They have given me the two codes.
First one displays a table but I have had to manually enter each table header and it is not dynamic
function my_attendee_form (){
$people = array();
$EM_Bookings = $EM_Event->get_bookings();
if( count($EM_Bookings->bookings) > 0 )
{
echo "\n";
?>
<table class="event-attendees">
<tr class="">
<th class="attendee-name">Name</th>
<th class="attendee-country">Golf Link</th>
<th class="attendee-discipline">Handicap</th>
<th class="attendee-status">Home Club</th>
</tr>
<?php
$guest_bookings = get_option('dbem_bookings_registration_disable');
$guest_booking_user = get_option('dbem_bookings_registration_user');
$counter = 0;
foreach( $EM_Bookings as $EM_Booking){
$attendees_list = "";
$attendees = $EM_Booking->booking_meta['attendees'];
if ( !empty($attendees) ) {
$attendees_list = "";
foreach($attendees as $key => $value) {
foreach($value as $key_attendee => $value_attendee) {
$attendees_list .= "<tr>";
$attendees_list .= "<td>".$value_attendee["attendee_name"]."</td>";
$attendees_list .= "<td>".$value_attendee["golflink"]."</td>";
$attendees_list .= "<td>".$value_attendee["handicap"]."</td>";
$attendees_list .= "<td>".$value_attendee["home_club"]."</td>";
$attendees_list .= "</tr>";
}
}
}
echo $attendees_list;
}
echo "\n";
?>
</table>
<?php
}
if( count($EM_Bookings->bookings) == 0 )
{
echo '<p>No one registered yet... Will you be the first ?</p>'};
}
add_action('em_bookings_event_footer', 'my_attendee_form');
This is slightly broken, the table works.
The second bit of code adds a column to an existing table and populates it based on the form fields.
function my_em_bookings_table_cols_template_attendee2($template, $EM_Bookings_Table){
$template['attendee_name'] = 'Attendee Name';
return $template;
}
add_action('em_bookings_table_cols_template', 'my_em_bookings_table_cols_template_attendee2',10,2);
function my_em_custom_booking_form_cols_attendee_list($val, $col, $EM_Booking, $EM_Bookings_Table, $csv){
if( $col == 'attendee_name' ){
$EM_Tickets_Bookings = $EM_Booking->get_tickets_bookings();
$attendee_datas = EM_Attendees_Form::get_booking_attendees($EM_Booking);
$attendee_list = "";
foreach( $EM_Tickets_Bookings->tickets_bookings as $EM_Ticket_Booking ){
//Display ticket info
if( !empty($attendee_datas[$EM_Ticket_Booking->ticket_id]) ){
$val .= "<ul>";
$val .= "<li> <strong>Ticket name: ".$EM_Ticket_Booking->get_ticket()->ticket_name."</strong></li>";
foreach( $attendee_datas[$EM_Ticket_Booking->ticket_id] as $attendee_title => $attendee_data ){
$val .= "<li>".$attendee_title."</li>";
$val .= "<li><ul>";
foreach( $attendee_data as $field_label => $field_value){
$val .= "<li>". $field_label .': '.$field_value."</li>";
}
$val .= "</ul></li>";
}
$val .= "<ul>";
}
}
}
return $val;
}
add_filter('em_bookings_table_rows_col','my_em_custom_booking_form_cols_attendee_list', 10, 5);
How would I combine these two so that I can generate a new table like the first code, but populate it like the second one? I just don't know what goes where.
Any suggestions/thoughts would be great.
Thanks
Troy

PHP: For each different key value, group together

I have this mysql sample table:
+----+---------------+-------+
| id | company | value |
+----+---------------+-------+
| 1 | google | 50 |
+----+---------------+-------+
| 2 | microsoft | 24 |
+----+---------------+-------+
| 3 | google | 12 |
+----+---------------+-------+
| 4 | microsoft | 89 |
+----+---------------+-------+
| 5 | stackoverflow | 45 |
+----+---------------+-------+
And I want to print it as such so that they are grouped by company:
<ul class="google">
<li>50</li>
<li>12</li>
</ul>
<ul class="microsoft">
<li>24</li>
<li>89</li>
</ul>
<ul class="stackoveflow">
<li>45</li>
</ul>
This is my current code:
$resultx = mysql_query();
$temp=0;
$p = array();
while ($row = mysql_fetch_array($resultx)) {
$p[$temp]['id']=$row['id'];
$p[$temp]['company']=$row['company'];
$p[$temp]['value']=$row['value'];
$temp++;
}
foreach ($p as $obj) {
echo '<ul class="'.$obj["company"].'"><li>'.$obj["value"].'</li></ul>';
};
But my code prints all the company together.
EDIT:
I want to group the company in different UL's.
I would assume that I would have to use another foreach inside my foreach.
When building your array, make the key of the array be the company name or company id. Since I don't see a company id in your query, I will go with name. Now have it be a multidemsional array, with the inner array beging the values.
$resultx = mysql_query();
$p = array();
while ($row = mysql_fetch_array($resultx)) {
$p[$row['company']]['id']=$row['id'];
$p[$row['company']]['company']=$row['company'];
$p[$row['company']]['values'][]=$row['value'];
}
foreach ($p as $obj) {
echo '<ul class="'.htmlspecialchars($obj["company"]).'">';
foreach ($obj['values'] as $value) {
echo '<li>'.htmlspecialchars($value).'</ul>';
}
echo '</ul>';
};
Let us begin:
SELECT * FROM `yourTableName` ORDER BY `company`
Then you do this:
for($i = 0; $i<sizeOf($p); $i++)
{
if ($p[$i] == 0 || $p[$i]['company'] != $p[$i-1]['company'])
echo '<ul class="'.$obj["company"].'">';
ecoh '<li>'.$obj["value"].'</li>';
if ($p[$i] == 0 || $p[$i]['company'] != $p[$i-1]['company'])
echo '</ul>';
}
$resultx = mysql_query();
$temp=0;
$companies = array();
while ($row = mysql_fetch_array($resultx)) {
$companies[$row['company']][]=$row;
}
foreach ($companies as $company=>$values) {
echo '<ul class="'.$company.'">';
foreach($values as $value){
echo '<li>'.$value["value"].'</li>';
}
echo'</ul>';
}
There are of course other ways to do it, to make it simple I used 2 different loops.
$companies = array();
//One array that will have companies' names as keys
// and the value would be an array of values.
$resultx = mysql_query();
while ($row = mysql_fetch_array($resultx)) {
$companies[ $row['company'] ][] = $row['value'];
}
foreach ($companies as $company => $values) { //Loop the companies
echo '<ul class="'.$company.'">';
foreach($values as $value) //Loop the values of that company
{
echo '<li>'.$value.'</li>';
}
echo '</ul>';
}
** Haven't tested it.
I hope that this will solve your problem
$p = array(array());
while ($row = mysql_fetch_array($resultx)) {
$p[$row['company']][] = $row['value'];
}
foreach ($p as $key => $obj) {
echo '<ul class="'.$key.'">';
foreach ($obj as $val) {
echo '<li>'.$val.'</li>';
}
echo '</ul>';
};

how to display result of query

After query I try to display data. I can receive only data from 'field_1[]'. From 'field_2[]' and from 'field[]' no. How to fix it?
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_rows($result);
//------------------------------------------------------------------
for($i_1=0; $i_1<$fields_num; $i_1++)
{
$field_1 = mysql_fetch_assoc($result);
echo "<td>a".$field_1['index_period_1']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_assoc($result);
echo "<td>b".$field['index_period']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------
for($i_2=0; $i_2<$fields_num; $i_2++)
{
$field_2 = mysql_fetch_assoc($result);
echo "<td>c".$field_2['index_period_2']."</td>";
}
edit:----------------------
|------------|period_1 |period_1 |period_1 |
-----------------------------------------------
|period_2 |period |period |period |
-----------------------------------------------
|period_2 |period |period |period |
-----------------------------------------------
You are sort of missing the point of mysql_fetch_assoc() and rows in MySQL:
while ($row = mysql_fetch_assoc($result)) {
echo $row['index_period'];
echo $row['index_period_1'];
echo $row['index_period_2'];
}
You call mysql_fetch_assoc() once per row.
I'm not really sure why you need to loop over your table like this, but I won't interrogate you.
This might fit your needs (I cringe writing this):
$index_period = array();
$index_period_1 = array();
$index_period_2 = array();
while ($row = mysql_fetch_assoc($result)) {
$index_period[] = $row['index_period'];
$index_period_1[] = $row['index_period_1'];
$index_period_2[] = $row['index_period_2'];
}
foreach ($index_period as $value) {
echo "<td>a" . $value . "</td>";
}
foreach ($index_period_1 as $value) {
echo "<td>b" . $value . "</td>";
}
foreach ($index_period_2 as $value) {
echo "<td>c" . $value . "</td>";
}
Once you finish your first for loop, you have iterated through the entire result set. So when you enter your next for loop, there is nothing left to iterate and mysql_fetch_assoc() returns false. If you want to reset the internal data pointer, you can call
mysql_data_seek($result, 0);
This will enable you to re-iterate through the result set in your next for loop.

Categories