I have a multi-columns HTML table generated by PHP with Array, taking data from a table in a database which contains a list of entries. One of the 5 columns is a datestamp. I would like the HTML table to be sorted by timestamp, without any code it sorts it by ID (column0).
Here is the code I have to sort:
$table .= "<tr><td>" . $column0[$i][0] ."</td><td>" . $column1[$i][1] . "</td><td>" . $column2[$i][2] . "</td><td>" . $column3[$i][3] . "</td><td>" . $column4[$i][4] . "</td><td>" . $column5[$i][5] . "</td></tr>";
$column5[$i][5] is the one containing the datestamp. I've tried sort(), asort(), array_multisort()... without any luck.
Here is the SQL table structure:
column0: id
column1: number1
column2: text1
column3: number2
column4: text2
column5: date (format: Y-m-d H:m:s)
And here is an example of its content, for which I need to sort by the column date:
id.....number1.....text1.....number2.....text2................date
1........75.............toto..........58...........tata.......2014-04-07 16:43:51
2........34.............tutu..........07...........titi.........2013-04-09 08:27:34
3........83.............tyty..........53...........tete.......2015-04-08 12:36:18
Thank you!
You can use usort() and compare date by strtotime(). An example here..
$arr = array(
0 => array('id'=>1,'number1'=>'75','text1'=>'toto','number2'=>'58','text2'=>'tata','date'=>'2014-04-07 16:43:51',),
1 => array('id'=>2,'number1'=>'34','text1'=>'tutu','number2'=>'07','text2'=>'titi','date'=>'2013-04-09 08:27:34',),
2 => array('id'=>3,'number1'=>'83','text1'=>'tyty','number2'=>'53','text2'=>'tete','date'=>'2015-04-08 12:36:18',),
);
function sort_by_date($a, $b) {
$a = strtotime($a['date']);
$b = strtotime($b['date']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($arr, 'sort_by_date');
$keys = array_keys(current($arr));
$html = '<table border="1"><tr>';
foreach($keys as $key){
$html .= '<th>'.$key.'</th>';
}
$html .= '</tr>';
foreach($arr as $value){
$html .= '<tr>';
foreach($value as $val){
$html .= '<td>'.$val.'</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
Output:
Related
I am so close to figuring this out, this is using Wordpress and Gravity Forms Plugin:
<?php
$form_id = '1'; // The registration form's ID
$entries = GFAPI::get_entries( $form_id ); // Get all entries
$html = "<table class='ent'>"; // Create an HTML table
$html .= "<tr><th>Name</th><th>Organization</th><th>Event</th><th>Date</th><th>Number Attending</th></tr>";
$list = array(); // Array to store the original fields
$used = array(); // Array to stored the "used" fields
// Loop through array of entries,each element
foreach($entries as $entry){
// Get datepart from datetime of event and today's date
$date = date_format(new DateTime($entry['8']), 'Y-m-d');
$today = date("Y-m-d");
// Compare event's date with current date
if ( $date >= $today ) {
$list[] = $entry;
if (!empty($used[$entry['6']])) // If used[event name] not null then sum associated numattend
{
$used[$entry['6']] += $entry['5'];
}
else // return associated numattend
{
$used[$entry['6']] = $entry['5'];
}
}
}
unset($entry);
foreach ($used as $key => $value) {
foreach ($list as $key1 => $value1) {
$html .= "<tr><td>" . $value1['1'] . " " . $value1['2'] . "</td><td>" . $value1['93'] . "</td><td>" . $value1['6'] . "</td><td>" . $value1['8'] . "</td><td>" . $value1['5'] . "</td></tr>";
}
$html .= "<tr class='ent_sum_rw'><td>" . " " . "</td><td>" . " " . "</td><td>" . " " . "</td><td class='ent_sum'>" . "Total Attending:" . "</td><td>" . $value . "</td></tr>";
}
unset($value);
$html .= "</table>";
return $html;
?>
Result:
I want the loop to end the entry list on the corresponding "Event Name", Like "Test Event 22" should not show up on the top entry list.
The trick is to populate an Array that meets your demands and after that convert it to html. I haven't tested the code, but it should be clear how it works.
$aEventList = Array();
foreach($entries as $entry){
if (!isset($aEventList[$entry['7']])){ //7 is id of event
//if this event is not made, create it and add name and the date, enter the right numeral
$aEventList[$entry['7']]['name'] = $entry['6'];
$aEventList[$entry['7']]['date'] = $entry['90'];
$aEventList[$entry['7']]['users'] = Array();
}
$aEventList[$entry['7']]['users'][] = Array('name' => $entry['1'] . ' '. $entry['2'],
'org' => $entry['93'],
'num' => $entry['5']);
}
//now you've populated every event and you can loop through it on your desired way:
foreach ($aEventList as $iEvent => $aEvent){
echo $aEvent['name']; //event name
echo $aEvent['date']; // event date
foreach ($aEvent['users'] as $aEventUser){
echo $aEventUser['name']; // user name
echo $aEventUser['org']; // user organisation
echo $aEventUser['num']; // num attendees
}
}
I have an array that i pull from a database that looks like this
id - name - shortlink - downloadurl - count - date
Now I want to display that array as a table so the administartor of the site can se the content of the database. For that, I'm using this code:
function build_table($array){
// start table
$html = '<table id="usertable">';
// header row
$html .= '<tr class="header">';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
And it works great.
The problem is that i wan't do display some of the columns with a different code. E.g. 'downloadurl' which is an webadress, i want to make clickable. I just can't figure out how to split up the function so that i can write the code for the individual columns.
You could try something similar to the following:
using conditionals
This is probably the most straight forward way to go about handling different attributes per column - not without its drawbacks (noted below)
// data rows
foreach( $array as $key => $value) {
$html .= '<tr>';
foreach($value as $key2 => $value2) {
if ($key2 == 'downloadurl') {
$html .= '<td>Download</td>';
} else {
$html .= '<td>' . $value2 . '</td>';
}
}
$html .= '</tr>';
}
using switch statement
If you decide on this route, it may be a bit easier to manage in the long run as if () elseif () else() can become difficult to read over time.
foreach($value as $key2 => $value2) {
switch($key2) {
case 'downloadurl':
$html .= '<td>Download</td>';
break;
default:
$html .= '<td>' . $value2 . '</td>';
}
}
use this function to generate urls:
function getURL($downloadURL)
{
$html = "<a href = '$downloadURL'>Download</a>";
return $html;
}
And your function build_table():
function build_table($array){
// start table
$html = '<table id = "usertable">';
// header row
$html .= '<tr class = "header">';
foreach($array[0] as $key => $value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key => $value){
$html .= '<tr>';
foreach($value as $key2 => $value2){
$value2 = ($key2 == 'downloadurl') ? getURL($value2) : $value2;
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
When I think about the functional of array and I tried to create an array and store in the function acts as the clock but how can I get the array values outside the function?
function theClock($a,$b,$c){
$time['Hour'] = $a;
$time['Minute'] = $b;
$time['Seconds'] = $c;
return $time;
}
//How can I call the array values in there that $time is stored?
I am a beginner of PHP and I want to improve my concept, I am very grateful if anyone can helps, Cheers!
Sorry, I forgot to mention that I would like to use foreach() to shows the array values as the table form.
$show1 = '<table border ="1" >';
foreach($time as $ck => $tk){
$show1 .= '<tr><td>' . $ck . '</td><td>' . $tk . '</td></tr>';
}
$show1 .= '</table>';
$show2 = '<table border ="1">';
foreach($time as $tk){
$show2 .= '<td>' . $tk . '</td>';
$show2 .= '<td>:</td>';
}
$show2 .= '</table>';
echo $show1;
echo $show2;
theClock(11,12,13);
function clock($a,$b,$c){
$time['Hour'] = $a;
$time['Minute'] = $b;
$time['Seconds'] = $c;
return $time;
}
$time = clock(12, 30, 00);
$hour = $time['Hour'];
$minute = $time['Minute'];
$seconds = $time['Seconds'];
print $hour; // 12
print $minute; // 30
print $seconds; // 00
As per your edit, to use in a foreach loop:
$html = '<table border ="1" >';
foreach($time as $unit => $value){
$html .= "<tr><td>$unit:</td><td>$value</td></tr>";
}
$html .= '</table>';
You can do this by just calling your function with your parameters like
$time = clock(10,20,30);
try this
$vararr=clock($a,$b,$c);
$time = clock(12, 40, 15);
echo "<pre>";print_r($time);
I want to print column sub headings on some specific columns .. how can I print them dynamically?
Something like that ..
col heading 1 col heading 2 col heading 3
------------- ------------- -------------------------
col1 col2 col1 col2 col1 col2 col3 col4
<?php
$recievedArray = array(array("abc def", "abc ghi", "abc jkl"),
array("123 456", "123 789")); //Consider you getting the result from db to php as array
/**
*
* #param array $array Two dimentional array to format
* #return string
*/
function formatter(Array $array)
{
foreach ($array as $key => $value) {
$sub = '';
foreach ($value as $subKey => $subValue) {
$sub .= strstr($subValue, ' '); //Get string after first space
$exploded[strstr($subValue, ' ', TRUE)] = $sub; //Get string before first space
}
}
$html = '';
$tableStart = '<table>';
$tabeEnd = '</table>';
$th = '';
$td = '';
$lineTd = '';
$trStart = '<tr>';
$trEnd = '</tr>';
//Here th and td are prepared
foreach ($exploded as $key => $value) {
$th .= '<th>' . $key . '</th>';
$lineTd .= '<td>' . str_repeat('--', strlen($value)) . '</td>';
$td .= '<td>' . $value . '</td>';
}
//Concatenate the string to get the formated table data
$html .= $tableStart .
$trStart .
$th .
$trEnd .
$trStart .
$lineTd .
$trEnd .
$trStart .
$td .
$trEnd .
$tabeEnd;
return $html;
}
echo formatter($recievedArray);
I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;