I have an array of arrays and accessing the data is fine, but when I try to create separate tables based on a key, which is set to the numeric month that the data pulled from the database falls under.
I have:
array(1) {
[5]=>
array(12) {
["ID"]=>
string(5) "1001"
["created_timestamp"]=>
string(26) "2015-06-11 19:10:00"
["firstname"]=>
string(4) "John"
["lastname"]=>
string(3) "Doe"
}
}
array(1) {
[5]=>
array(12) {
["ID"]=>
string(5) "1002"
["created_timestamp"]=>
string(26) "2015-06-12 19:10:00"
["firstname"]=>
string(4) "Jane"
["lastname"]=>
string(3) "Doe"
}
}
array(1) {
[6]=>
array(12) {
["ID"]=>
string(5) "1003"
["created_timestamp"]=>
string(26) "2015-07-16 19:20:00"
["firstname"]=>
string(4) "John"
["lastname"]=>
string(4) "John"
}
}
The [5] Represents the current month -1. What I want to do is create a table and headers but only once, then populate the table with first and last name.
foreach($m as $key => $value)
{
if(key($m) != $currentKey)
{
$currentKey = key($m);
}
if($key == date("n", strtotime($value['created_timestamp']))-1);
{
for($i=$currentKey; $i<=$lastkey; $i++) {
echo "<br>".count($key);
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
$table .= '<tr><td>'.date("F Y", strtotime($m[$currentKey]['created_timestamp'])).'</td><td>' . $value['ID'] . '</td><td>' . $value['lastname'] . ' ' . $value['firstname'] . '</td></tr>';
$table .= '</tbody>';
$table .= '</table>';
}
}
}
Whenever I run the code it creates a table for each separate array. I want to create one table for each separate month and populate it with anything with the same key. I feel like I'm missing something though. Any help would be greatly appreciated!
A dirty solution. Since info is lacking
Here are a few assumptions:
- Array is sorted in ASC order
- There is only one item in each array [ID, Name, Timestamp]
- IF there are more items, then you can just add a loop in there
- $m is the multi-dimensional array.
NOTE: Not tested.
$currentKey = 0;
$count= 0;
$lastKey = count($m) - 1;
foreach($m as $key => $value) {
if(key($m) != $currentKey) {
$currentKey = key($m);
if($count== 0) {
echo "<br>".count($key);
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
} else {
$table .= '</tbody>';
$table .= '</table>';
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
}
}
if($key == date("n", strtotime($value['created_timestamp']))-1) {
$table .= '<tr><td>'.date("F Y", strtotime($value['created_timestamp'])).'</td><td>' . $value['ID'] . '</td><td>' . $value['lastname'] . ' ' . $value['firstname'] . '</td></tr>';
}
if($lastKey == $count) {
$table .= '</tbody>';
$table .= '</table>';
}
$count++;
}
Related
I am pulling data lines from a .txt file and I am attempting to insert it into an HTML table. Right now I am stuck on outputting the array. I am able to turn the line I exploded into an array by re-exploding the line. I var_dumped the new line to ensure it is an array. I need to return a function that outputs the data into an HTML table. I do not know where to go from here. Any help is appreciated. This is as far as I got. For the sample there are about 10 books in the .txt file. Do I include HTML in the same function? or outside and how do I implement? Thank you.
PHP
function displayTable($filename)
{
$table = "\n<table border='1'>";
$table .= "<tr>";
$table .= "<th>Title</th>";
$table .= "<th>Author</th>";
$table .= "<th>ISBN</th>";
$table .= "<th>City</th>";
$table .= "</tr>\n\n";
$line_ctr = 0;
$fp = fopen($filename, 'r'); //op
ens the file for reading
if ($fp)
{
while(true)
{
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
//Explode into string
list($title, $author, $isbn, $city) = explode('*', $line);
$new_line = explode('*', $line);
var_dump($new_line);
}
fclose($fp ); //Close file
}
CURRENT OUTPUT SAMPLE
array(5) { [0]=> string(14) "Smart Living" [1]=> string(7) "health" [2]=> string(10) "2005-09-12" [3]=> string(13) "1-4145-5896-x" [4]=> string(2) " " }
array(5) { [0]=> string(14) "Make Money Sleeping" [1]=> string(7) "health" [2]=> string(10) "2009-01-08" [3]=> string(13) "1-4888-5896-x" [4]=> string(2) " " }
I saw your commnet. You want to sort the table. I've rewritten this function, hopefully, to help you.
You can split it to 3 step: 1.read file, 2.sort data, 3.output HTML.
function displayTable($filename)
{
// 1. read file to array
$data = array(); // Save all data read from txt file.
$fp = fopen($filename, 'r'); //opens the file for reading
if ($fp) {
while (true) {
$line = fgets($fp);
if (feof($fp)) {
break;
}
$new_line = explode('*', $line);
$data[] = $new_line; // save to data
}
fclose($fp); //Close file
}
// 2. sort data, example for sort by ISBN
if ($data) {
foreach ($data as $key => $value) {
$ISBN[$key] = $value[2]; //sort by ISBN
}
array_multisort($ISBN, SORT_ASC, $data);
}
// 3. output to HTML
$table = "\n<table border='1'>";
$table .= "<tr>";
$table .= "<th>Title</th>";
$table .= "<th>Author</th>";
$table .= "<th>ISBN</th>";
$table .= "<th>City</th>";
$table .= "</tr>\n\n";
foreach ($data as $key => $value) {
$table .= "<tr><td>" . join("</td><td>", $value) . "</td></tr>";
}
$table .= "</table>";
return $table;
}
$new_line = explode('*', $line);
$table .= "<tr><td>" . join("</td><td>", $new_line) . "</td></tr>";
}
return $table;
I added a new array to an existing array, but the layout is broken.
The code to output the array is:
for ($i=1; $i<=$comp_value_count; $i++) {
$compPro = 'pro'.$i;
$attrCount = $result[$compPro][11];//A count of how many options there are per product
$compDescription .= '<td>' . $result[$compPro][2] . '</td>';
$compModel .= '<td>' . $result[$compPro][3] . '</td>';
$compWeight .= '<td>' . $result[$compPro][4] . '</td>';
$compQuantity .= '<td>' . $result[$compPro][5] . '</td>';
$compManufacturer .= '<td>' . $result[$compPro][7] . '</td>';
$compattr1 .= '<td>';
for ($c=0; $c<=$attrCount; $c++){
$compattr2 .= $result[$compPro][8][$c] . $result[$compPro][9][$c] . "\n";
}
$compattr3 .= '</td>';
}
// create the display
echo '<tr class="rowEven"><th>' . COMPARE_QUANTITY . '</th>' . $compQuantity . '</tr>';
echo '<tr class="rowOdd"> <th>' . COMPARE_MODEL . '</th>' . $compModel . '</tr>';
echo '<tr class="rowEven"><th>' . COMPARE_WEIGHT . '</th>' . $compWeight . '</tr>';
echo '<tr class="rowOdd"> <th>' . COMPARE_MANUFACTURER . '</th>' . $compManufacturer . '</tr>';
echo '<tr class="rowEven"><th>' . COMPARE_DESC . '</th>' . $compDescription . '</tr>';
echo '<tr class="rowOdd"> <th>' . COMPARE_OPTNAME . '</th>' . $compattr1 . $compattr2 . $compattr3 . '</tr>';
echo '</table>';
}
A fiddle showing the layout this code generates is https://jsfiddle.net/uzmk61v7/2/
And another showing what I wanted it to look like is here https://jsfiddle.net/85wztu3z/1/
var_dump($result) output is below
array(2) {
["pro1"]=> array(12) {
[0]=> string(191) "01 button stainless steel audio panel - surface"
[1]=> string(612) "01 button stainless steel audio panel - surface"
[2]=> string(144) "5101S - 1 button audio door entry phone intercom panel SRS surface mounted, vandal resistant 1 way traditional audio, BS316 stainless steel,..."
[3]=> string(5) "5101S"
[4]=> string(1) "0"
[5]=> string(1) "1"
[6]=> string(171) "£147.74 Inc VAT £123.12 Ex VAT"
[7]=> string(3) "SRS"
[8]=> array(4) {
[0]=> string(12) "Call Buttons"
[1]=> string(8) "Mounting"
[2]=> string(6) "Finish"
[3]=> string(5) "Range"
}
[9]=> array(4) {
[0]=> string(20) "1 call button"
[1]=> string(20) "Surface mount"
[2]=> string(35) "Stainless Steel VR (brushed)"
[3]=> string(15) "SRS 5000"
}
[10]=> string(73) "remove"
[11]=> string(1) "4"
}
["pro2"]=> array(12) {
[0]=> string(200) "00 way VR brass video panel, size D"
[1]=> string(576) "00 way VR brass video panel, size D"
[2]=> string(148) "6600 - 0 button video door entry phone intercom panel Size D SRS vandal resistant 0 way traditional video, polished brass, engravable, door entry..."
[3]=> string(4) "6600"
[4]=> string(1) "0"
[5]=> string(1) "0"
[6]=> string(171) "£155.95 Inc VAT £129.96 Ex VAT"
[7]=> string(3) "SRS"
[8]=> array(4) {
[0]=> string(8) "Mounting"
[1]=> string(6) "Finish"
[2]=> string(5) "Range"
[3]=> string(7) "Cabling"
}
[9]=> array(4) {
[0]=> string(18) "Flush mount"
[1]=> string(21) "Polished brass"
[2]=> string(15) "SRS 4000"
[3]=> string(34) "SRS Video C + 6 + n cabling"
}
[10]=> string(73) "remove" [11]=> string(1) "4"
}
}
Any suggestions on how I can fix this?
Just add one more <td></td>
for ($i=1; $i<=$comp_value_count; $i++) {
$compPro = 'pro'.$i;
$attrCount = $result[$compPro][11];//A count of how many options there are per product
$compDescription .= '<td>' . $result[$compPro][2] . '</td>';
$compModel .= '<td>' . $result[$compPro][3] . '</td>';
$compWeight .= '<td>' . $result[$compPro][4] . '</td>';
$compQuantity .= '<td>' . $result[$compPro][5] . '</td>';
$compManufacturer .= '<td>' . $result[$compPro][7] . '</td>';
$compattr1 .= '<td>';
for ($c=0; $c<=$attrCount; $c++){
$compattr1 .= $result[$compPro][8][$c] . "\n";
}
$compattr1 .= '</td>';
$compattr2 .= '<td>';
for ($c=0; $c<=$attrCount; $c++){
$compattr2 .= $result[$compPro][9][$c] . "\n";
}
$compattr2 .= '</td>';
}
// create the display
echo '<tr class="rowEven"><th>' . COMPARE_QUANTITY . '</th>' . $compQuantity . '</tr>';
echo '<tr class="rowOdd"> <th>' . COMPARE_MODEL . '</th>' . $compModel . '</tr>';
echo '<tr class="rowEven"><th>' . COMPARE_WEIGHT . '</th>' . $compWeight . '</tr>';
echo '<tr class="rowOdd"> <th>' . COMPARE_MANUFACTURER . '</th>' . $compManufacturer . '</tr>';
echo '<tr class="rowEven"><th>' . COMPARE_DESC . '</th>' . $compDescription . '</tr>';
echo '<tr class="rowOdd"> <th>' . COMPARE_OPTNAME . '</th>' . $compattr1 . $compattr2 . '</tr>';
echo '</table>';
Sample Query 1 -
SELECT ID,NAME FROM USERS
Sample Query 2 -
SELECT Orders.OrderID as ID, Customers.CustomerName as Name, Orders.OrderDate as Date
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
How can I load title headings to an array in PHP?
I mean
ID,NAME in Query 1 and ID,Name,Date in Query 2
This is what I'm trying to do :
I'm creating a PHP function to make HTML table automatically from any given MySQL-Select query
This where I'm up to now
function createTable($query) {
$sql_link = Connect_MySQLi_DB();// Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
$headings = array('ID','Name','Date');//I need this array to create automatically
echo '<table>';
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<th>'.$headings[$x].'</th>';
}
echo '<tr>';
while ($row = $result->fetch_object()) {
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<td>' . $row->$headings[$x] . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
So I need to create that $heading array automatically.
If I can do that, this function can display any MySQL-Select query as a HTML table
If you are using mysqli then fetch_fields seems to do the job.
EDIT:
Example:
$res = $db->query('SELECT A.id,A.a,A.id + B.id AS idd FROM A natural join B');
var_dump($res->fetch_fields());
Returns information about columns A.id, A.a and about the idd column (both tables have other columns). I omitted some fields from the output in order to make it shorter.
array(3) {
[0]=>
object(stdClass)#3 (13) {
["name"]=>
string(2) "id"
["orgname"]=>
string(2) "id"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[1]=>
object(stdClass)#4 (13) {
["name"]=>
string(1) "a"
["orgname"]=>
string(1) "a"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[2]=>
object(stdClass)#5 (13) {
["name"]=>
string(3) "idd"
["orgname"]=>
string(0) ""
["table"]=>
string(0) ""
["orgtable"]=>
string(0) ""
// more fields here
}
}
Finally this is how I made this function to work (Thanks Hynner for your excellent suggestion),
function createTable_from_sql_select_query($query) {
$sql_link = Connect_MySQLi_DB();// Database connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
// Adding Missing array_column Function for Old PHP Versions (<5.5)
if (!function_exists('array_column')) {
function array_column($array, $column) {
$ret = array();
foreach ($array as $row)
$ret[] = $row[$column];
return $ret;
}
}
$headings = json_decode(json_encode($result->fetch_fields()), true);
$headings = array_column($headings, 'name');
$return = '<table>';
$return .= '<thead><tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<th>' . ucwords(str_replace('_', ' ', (strtolower($headings[$x])))) . '</th>';
}
$return .= '</tr></thead><tbody>';
while ($row = $result->fetch_object()) {
$return .= '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<td>' . $row->$headings[$x] . '</td>';
}
$return .= '</tr>';
}
$return .= '</tbody></table>';
return $return;
}
Now anyone can convert any SQL select query to a HTML table.
Hy,
how I retrieve information from an associative array like list in php.
var_dump shows something like this:
array(2) { [1]=> string(1) "1"
[2]=> string(1) "2" }
array(2) { [1]=> string(15) "gica_craioveanu"
[2]=> string(14) "alexandra_minu" }
array(2) { [0]=> string(10) "craiovaMAX"
[1]=> string(10) "alexMinu10" }
First array containd the id's, second the user name and third the passwords.
My attempt:
foreach ($row as $i => $id,$user_name,$user_pass) {
echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
}
one of php file contains the script to construct the list:
while($row = mysqli_fetch_row($result))
{
/*$id[]=$row['user_id'];
$user_name[]=$row['user_name'];
$user_pass[]=$row['user_pass'];
$i=$i+1;*/
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
/*for($no=0; $no<$i; $no++){
echo $row[$i]."/".$row[$i]."/";
}*/
include 'user.html.php';
}
?>
and the user.html.php
to view the rows:
<?php
// while (list($id, $user_name, $user_pass)= each($row)) {
foreach($row as $i => $id,$user_name,$user_pass){
echo " <tr>\n" .
" <td>".$id."</td>\n".
" <td>".$user_name."</td>\n".
" <td>".$user_pass."</td>\n".
" </tr>\n";
/*echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
*/
/*for($no=0; $no<$i; $no++){
echo "<tr>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"</tr>";*/
}
?>
while($row = mysqli_fetch_row($result)) {
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
...
for($i = 1; $i < count($id) + 1; $i++) {
echo " <tr>\n" .
" <td>".$id[$i]."</td>\n".
" <td>".$user_name[$i]."</td>\n".
" <td>".$user_pass[($i - 1)]."</td>\n".
" </tr>\n";
}
$id = array("1", "2");
$user_name = array("gica_craioveanu", "alexandra_minu");
$user_pass = array("craiovaMAX", "alexMinu10");
We presume that 3 arrays are always the same size :
// You make a loop on first array
for ( $i = 0 ; $i < count($id) ; $i++ )
{
// You use index $i to access to 3 arrays.
echo 'ID: '.$id[$i].'<br />';
echo 'Name: '.$user_name[$i].'<br />';
echo 'Password: '.$user_pass[$i].'<br />';
}
for($no=1; $no<$i+1; $no++)
{
echo "<tr>".
"<td>".$id[$no]."</td>".
"<td>".$user_name[$no]."</td>".
"<td>".$user_pass[($no-1)]."</td>".
"</tr>";
}
Inspired by Typoheads
i got this array.
array(24) {
[0]=> array(3) {
["id"]=> string(1) "1"
["category"]=> string(5) "Alles"
["description"]=> string(0) ""
}
[1]=> array(3) {
["id"]=> string(2) "11"
["category"]=> string(6) "Cinema"
["description"]=> string(0) ""
}
[2]=> array(3) {
["id"]=> string(1) "8"
["category"]=> string(8) "Computer"
["description"]=> string(0) ""
}
}
And i dont know how to show this informations:
I tried with:
for ($x = 0; $x < sizeof($array); ++$x)
{
echo "key: ".key($array)."<br>value: ".current($array)."<br>";
next($array);
}
The Key value is now right, but the current-value is also an array :(
I hope someone can help.
Should be something like
foreach($array as $key => $value)
{
echo "key: " . ' '.$key .', '.
"category: " . ' ' . $value['category'].',
"description: " . ' ' . $value['description'];
}
Use nested foreach loops i.e.
foreach ($array as $key => $value){
echo "[ ".$key." ]<br/>";
foreach ($value as $innerKey => $innerValue){
echo $innerKey." => ".$innerValue."<br/>";
}
}
You could iterate over this array as follows:
foreach($sourceArray as $key => $value) {
echo 'Item: ' . $value . '<br />';
foreach($value as $subKey => $subValue) {
echo $subKey.' -> '.$subValue.'<br />';
}
}