Matching column with row according to data from array - php

I have two set off array, in one I hold colors in another dimensions. Those array I use to make queries and later print result in table.
$colors = array(
"27" => "RAL 9002",
"255" => "RAL 9006",
"341" => "RAL 8019",
"286" => "RAL 7016",
"141" => "RAL 3009",
"171" => "RAL 6028",
"121" => "RAL 8004",
"221" => "RAL 5010",
"101" => "RAL 3000",
"273" => "RAL 9007");
$dimensions = array
(
array(0.3,1245),
array(0.35,1245),
array(0.40,1100),
array(0.45,1245),
array(0.50,1245),
array(0.60,1245),
array(0.70,1245)
);
According to the values above I make query:
foreach($colors as $key => $value)
{
foreach($dimensions as $data )
{
$sql = "SELECT sum(Kolicina) as suma
FROM materijali WHERE Debljina = $data[0] AND Sirina = $data[1] AND Boja = $key";
$q = $conn->query($sql);
while($r=$q->fetch()) {
$debljina = $data[0];
$sirina = $data[1];
$kolicina = $r["suma"];
$kod = $key;
if(empty($kolicina)) {
$kolicina = '0.00';
}
$vrijednosti[] = $debljina.'x'.$sirina.'--'.$kod;
}
}
}
Result I receive from above I should print in table. For some reason I dont get good result, It always displays red. Not sure if I should use isset() function.
<div class="col-lg-6">
<table class="table table-bordered">
<thead>
<tr>
<th><?php echo "Dimenzije"; ?> </th>
<?php foreach($colors as $boja) { ?>
<th><?php echo $boja; ?> </th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach($dimensions as $dim) {
?>
<tr>
<td><?php
echo $dim[0] . ' X ' . $dim[1]; ?> </td>
<?php
foreach($colors as $key => $value) {
// if ($vrijednosti[$dim[0].'--'.$dim[1].'--'.$key]) {
if (isset($vrijednosti[$dim[0].'x'.$dim[1] .'--'.$key])) {
echo '<td style="background:blue"> </td>';
}
else {
echo '<td style="background:red">' .$vrijednosti[$dim[0].'x'.$dim[1] .'-'.$key] .' </td>';
}
}
?> </td>
</tr>
<?php }
?>
</tbody>
</table>
</div>
When I dump array $vrijednosti I get following format (I just took 5elements)
array(70) {
[0]=>
string(12) "0.3x1245--27"
[1]=>
string(13) "0.35x1245--27"
[2]=>
string(12) "0.4x1100--27"
[3]=>
string(13) "0.45x1245--27"
[4]=>
string(12) "0.5x1245--27"
Table does not show good results, dont have idea what could be wrong? Any help would be appreciated.
Table looks like this. Table forms looks well. In cells it should display $kolicina which I get in while loop.

$vrijednosti[] = $debljina.'x'.$sirina.'--'.$kod;
creates a numeric indexed array. But your if checks for the presence of an array key in $vrijednosti:
if (isset($vrijednosti[$dim[0].'x'.$dim[1] .'--'.$key])) { ... }
Thats always false. You have to check for an element, not a key:
if (in_array($dim[0].'x'.$dim[1] .'--'.$key, $vrijednosti) { ... }

Related

How to resolve Trying to access array offset on value of type null error?

WHAT:
So I cannot for the life of me figure out why I'm getting this error. I'm trying to create a function that will display the user information from the database in a table but I have like a ton of these errors on the page and I don't know whats wrong.
STEPS TO RESOLVE:
So I've gone over my code a bunch of types to make sure that all the variables and what not were spelled correctly and as far as I can tell they are.
I've also googled this issue to see if I can find a solution but none of them are very helpful.
I honestly don't know whats wrong so kinda hard to find ways to resolve an issue, I don't even really know what this error means.
THE CODE:
This is the function:
<?php
function display_table($fields, $data, $rows, $page){
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$firstRecord = ($page - 1) * ROWS_PER_PAGE;
$pageNumbers = ceil($rows / ROWS_PER_PAGE);
echo '<div class="table-responsive w-75 mx-auto py-3">
<table class="table table-dark table-bordered table-sm">
<thead>
<tr>';
foreach($fields as $key){
echo '<th class="py-2">' . $key . '</th>';
}
echo '</tr>
</thead>
</tbody>';
$keys = array_keys($fields);
for($record = $firstRecord; $record < $firstRecord + ROWS_PER_PAGE; $record++){
$row = $data[$record];
echo '<tr>';
for($recordCount = 0; $recordCount < count($keys); $recordCount++){
$column = $keys[$recordCount];
echo '<td class="py-2">' . $row[$column] . '</td>';
}
echo '</tr>';
}
echo '</tbody>
</table';
for($pages = 1; $pages <= $pageNumbers; $pages++){
echo '<a class="btn btn-dark mx-1" href=?page=' . $pages . '</a>';
}
}
?>
This is where the function is put into action:
<?php
display_table(
array(
"id" => "Id",
"emailaddress" => "Email",
"firstname" => "First Name",
"lastname" => "Last Name",
"salesperson" => "Salesperson",
"phonenumber" => "Phone Number",
"extension" => "Extension",
"type" => "Type"
),
client_select_all(),
client_count(),
1
);
?>
Any help would be really appreciated.
NOTE: client_select_all and client_count are other functions, don't know if you'll need to see those or not

Print PHP array into table views with foreach

I'm newbie in development and I have trouble with this below logic.
This is my sample DB.
$data = array(3) {
$x_count = 2;
[1] => $name = 'A';
$y_count = 2;
array(2) {
[1] => $name = 'A.1';
$z_count = 2;
array(2) {
[1] => $name = 'A.1.a';
$val = 1;
[2] => $name = 'A.1.b';
$val = 1;
}
[2] => $name = 'A.2';
$z_count = 2;
array(2) {
[1] => $name = 'A.2.a';
$val = 2;
[2] => $name = 'A.2.b';
$val = 2;
}
}
[2] => $name = 'B';
$y_count = 2;
array(2) {
[1] => $name = 'B.1';
$z_count = 2;
array(2) {
[1] => $name = 'B.1.a';
$val = 3;
[2] => $name = 'B.1.b';
$val = 3;
}
[2] => $name = 'A.2';
$z_count = 2;
array(2) {
[1] => $name = 'B.2.a';
$val = 4;
[2] => $name = 'B.2.b';
$val = 4;
}
}
}
And I have to print like this
I have no idea of using foreach loop to print data into this table or caculating the number of "colspan" for each of x, y, z title.
I really hope to receive some advice. Thanks a lot!
EDIT: the x_count, y_count and z_count are variables get from DB and it's not only 2.
EDIT2: my expected result looks like this:
<table>
<tr>
<th>x_name</th>
<td colspan = "7">A</td>
<td colspan = "7">B</td>
<th rowspan = "3">SUM</th>
</tr>
<tr>
<th>y_name</th>
<td colspan = "3">A.1</td>
<td colspan = "3">A.2</td>
<td rowspan = "2">SUM</td>
<td colspan = "3">B.1</td>
<td colspan = "3">B.2</td>
<td rowspan = "2">SUM</td>
</tr>
<tr>
<th>z_name</th>
<td>A.1.a</td>
<td>A.1.b</td>
<td>SUM</td>
<td>A.2.a</td>
<td>A.2.b</td>
<td>SUM</td>
<td>B.1.a</td>
<td>B.1.b</td>
<td>SUM</td>
<td>B.2.a</td>
<td>B.2.b</td>
<td>SUM</td>
</tr>
<tr>
<th>value</th>
<td>1</td>
<td>1</td>
<td>2</td>
<td>2</td>
<td>2</td>
<td>4</td>
<td>6</td>
<td>3</td>
<td>3</td>
<td>6</td>
<td>4</td>
<td>4</td>
<td>8</td>
<td>14</td>
<td>20</td>
</tr>
</table>
You don't need to add y_count, x_count, you can use count() function on the object $data instead.
Here is HTML's structure I created, you may take a look
For data easier to process, you can consider to use my data structure below
$data = [
[
"name" => 'A', // x_name
"children" => [
[
"name" => 'A.1', // y_name
"children" => [
[
"name" => 'A.1.a', // z_name
"value" => 1
],
]
]
]
],
...
];
NOTE: All the code's logic below is used for your provided HTML, not for my jsFiddle's HTML
First step: Run a loop on every element of array $data for processing x_name data. Assign each row's html to variable for further use
/* Init html variable for $x_name, $y_name, $z_name, $value */
$x_html = '';
$y_html = '';
$z_html = '';
$value_html = '';
foreach ($data as $x_index => $x_data) {
$x_children = $x_data['children'];
$x_colspan = 1; // this variable will be sum of 1 'SUM' column and each $y_colspan
foreach ($x_children as $y_index => $y_data) {
$y_children = $x_data['children'];
$y_colspan = count($y_children) + 1; // all of y's children column + SUM column
// Update x_colspan
$x_colspan += $y_colspan;
// process assign html to $y_html
$y_html .= '<td colspan = "'.$y_colspan.'">'.$y_data['name'].'</td>';
// add SUM column
if ($y_index == count($x_children)-1) {
$y_html .= '<td>SUM</td>';
}
$sum = 0;
foreach ($y_children as $z_index => $z_data) {
$z_value = $z_data['value'];
$z_html .= '<td>'.$z_data['name'].'</td>';
// add SUM column for every looped 2 $z_data column
if ($z_index == count($y_children)-1) {
$z_html .= '<td>SUM</td>';
}
$sum += $z_value; // sum all value of current y_children
$value_html .= '<td>'.$z_data['value'].'</td>';
}
// After finish assign z_html, value_html, sum it all
$value_html .= '<td>'.$sum.'</td>'
}
$x_html .= '<td colspan = "'.$x_colspan.'">'.$x_data['name'].'</td>';
}
Last step: you print out all variable x_html, y_html, z_html, value_html. Merge it with the actual table html
$table_html = '
<table>
<tr>
<th>x_name</th>
'.$x_html.'
<th rowspan = "3">SUM</th>
</tr>
<tr>
<th>y_name</th>
'.$y_html.'
</tr>
<tr>
<th>z_name</th>
'.$z_html.'
</tr>
<tr>
<th>z_name</th>
'.$value_html.'
</tr>
</table>
';
This code above may be not runable, it's just a idea. Hope it would help you

get td values display as static in codeigniter

Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>

Match column and row, then print data

I am having two set off arrays, first array is holding data about colors, second about dimensions.
$colors= array(
"27" => "RAL 9002",
"255" => "RAL 9006",
"341" => "RAL 8019",
"286" => "RAL 7016",
"141" => "RAL 3009",
"171" => "RAL 6028",
"121" => "RAL 8004",
"221" => "RAL 5010",
"101" => "RAL 3000",
"273" => "RAL 9007",);
$dimensions = array
(
array(0.3,1245),
array(0.35,1245),
array(0.40,1100),
array(0.45,1245),
array(0.50,1245),
array(0.60,1245),
array(0.70,1245),
);
Values above are used for queries. I wanted to make an array which will hold data, and later in comparison will print data. Query can return result NULL
foreach($colors as $key => $value)
{
//print "Boja $key . <br>";
foreach($dimensions as $data )
{
//print "Debljina $data[0], Sirina $data[1] Boja $key <br>";
$sql = "SELECT Debljina, Sirina, sum(Kolicina) as suma
FROM jos_ib_repromaterijali WHERE Debljina = '$data[0]' AND Sirina = '$data[1]' AND Boja = '$key'";
$q = $conn -> query($sql);
$vrijednosti = array();
while($r=$q->fetch()) {
$debljina = $r['Debljina'];
$sirina = $r['Sirina'];
$kolicina = $r['suma'];
$vrijednosti[] = $debljina . $sirina . $kod . $kolicina;
}
}
}
Once I get results, I create html table
<div class="col-lg-6">
<table class="table table-bordered">
<thead>
<tr>
<th><?php echo "Dimenzije"; ?> </th>
<?php foreach($colors as $boja) { ?>
<th><?php echo $boja; ?> </th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach($dimensions as $dim) {
?>
<tr>
<td><?php echo $dim[0] . ' X ' . $dim[1]; ?> </td>
<td><?php
if (isset($vrijednosti[$dim[0] . $dim[1]])) {
echo "asdas";
}
else {
echo "error";
}
?> </td>
</tr>
<?php }
?>
</tbody>
</table>
Table print headers and dimensions as it should, I am having trouble in matching rows with column. If someone give me an advice it would be appreciated.
Query can give result NULL; if that is result It should print 0 below color for specific row.

Multi-Dimensional Sub-Array to Comma Separated List (PHP)?

The function works well for creating a formatted table from a multi-dimensional array and assigning it to a variable. When there is a sub-array it will nest another table nicely but instead, i'd like to display a comma-separated list (conditional only for sub-arrays).
What php function / logic could help me accomplish this and how should I implement it?
It currently displays this...
<table>
<tr>
<td><span style="color:#ffeeee;">Keywords</span></td>
<td>
<span style="color:#eeeeff;">
<table>
<tr>
<td><span style="color:#ccffcc;">Alex</span></td>
</tr>
<tr>
<td><span style="color:#ccffcc;">Mic</span></td>
</tr>
<tr>
<td><span style="color:#ccffcc;">snowboarding</span></td>
</tr>
</table>
</span>
</td>
</tr>
</table>
Would prefer something like this...
<table>
<tr>
<td><span style="color:#ffeeee;">Keywords</span></td>
<td><span style="color:#eeeeff;">Alex, Mic, snowboarding</span></td>
</tr>
</table>
PHP Code (display_array_processor.php):
//----------------------------------------------------//
/*
// Iterating complex php multidimensional multi-level array
// to html table using return instead of echo
*/
//----------------------------------------------------//
if($_POST)
{
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
$process_method = $_POST["process_method"];
$process_levels = $_POST["process_levels"];
//Sanitize input data using PHP filter_var()
//$process_method = filter_var($_POST["process_method"], FILTER_SANITIZE_STRING);
//----------------------------------------------------//
if ($process_levels == "noheaders") {
// Sample array from shell command (No Headings)...
$myArray = array(
array(
"Size" => "914 kB",
"Date" => "2015:02:08 18:01:00-08:00",
"Attributes" => "Regular; (none)",
"Names" =>
array(
"Alex Smith",
"Mike Jones"
),
"Keywords" =>
array(
2015,
"Alex",
"Mike",
"snowboarding",
array(
'A snow',
'B cold',
'C fun'
)
),
"Software" => "Invisible Space-Monkey Monitoring System 01",
"Duration" => 4800
)
);
} elseif ($process_levels == "headers") {
// Sample array from shell command (With Headings)...
$myArray = array(
array(
"SourceFile" => "test.txt",
"Tool" =>
array(
"Version" => 11.12
),
"File" =>
array(
"Size" => "104 kB",
"ModifyDate" => "2016:02:08 18:01:00-08:00"
),
"Region" =>
array(
"RegionAppliedToDimensionsUnit" => "pixel",
"RegionName" =>
array(
"Alex Smith",
"Mike Jones"
),
"Subject" =>
array(
2015,
"Alex",
"Mike",
"snowboarding"
)
)
)
);
} else {
// Small Sample Array...
$myArray = array(
"Source" => "test.txt"
);
}
if ($process_method == "tables") {
//$html = recursive_array($myArray);
$html = recursive_array_table($myArray);
} elseif ($process_method == "commas") {
$html = array_table($myArray);
} else {
$html = "Do not know the process method.";
}
//$html .= '<p><textarea rows="10" cols="75">'.$process_method.'</textarea></p>';
$output = json_encode(array('type'=>'message', 'text' => $html));
die($output);
}
//----------------------------------------------------//
// Recursive Array Functions - COMMA SUB-ARRAYS
//----------------------------------------------------//
// Two generic utility functions:
function is_nested($array) {
return is_array($array) && count($array) < count($array, COUNT_RECURSIVE);
}
function is_assoc($array) {
return is_array($array) && array_keys($array) !== range(0, count($array) - 1);
}
function array_table_row($key, $row) {
$content = array_table($row);
return "<tr>\n<th>$key</th>\n<td>$content</td>\n</tr>\n";
}
function array_table($array) {
if (is_nested($array) || is_assoc($array)) {
$content = implode("", array_map('array_table_row', array_keys($array), $array));
return "<table border=1>\n<tbody>\n$content</tbody>\n</table>\n";
}
// At this point $array is too simple for a table format:
$color = is_array($array) ? "922" : "292";
$content = htmlspecialchars(is_array($array) ? implode(", ", $array) : $array);
return "<span style='color:#$color'>$content</span>";
}
//----------------------------------------------------//
// Recursive Array Functions - TABLE SUB-ARRAYS (ORIG)
//----------------------------------------------------//
function recursive_array_table($array) {
return "<table border=1>\n<tbody>\n" .
recursive_array_table_row($array) .
//implode("", array_map('recursive_array_table_row', array_keys($array), $array)) .
"</tbody>\n</table>\n";
}
function recursive_array_table_row($array) {
foreach($array as $key => $value) {
$content .= '<tr>';
if (is_array($value)) {
$content .= '<td colspan="1"><span style="color:#992222;">'.htmlspecialchars($key).'</span></td>';
$content .= '<td><span style="color:222299;">'.recursive_array_table($value).'</span></td>';
} else {
// Filter out some info...
//if (
//($key != "Error") &&
//($key != "SourceFile")
//) {
//if (!is_numeric($key)) {
$content .= '<td>'.htmlspecialchars($key).'</td>';
//}
$content .= '<td><span style="color:#229922;">'.$value.'</span></td>';
//}
}
$content .= '</tr>';
}
return $content;
}
function recursive_array_csv($array) {
//return is_array($array)
// ? "[" . implode(", ", array_map('array_csv', $array)) . "]"
// : htmlspecialchars($array);
}
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#submit_btn").click(function() {
post_data = {
'process_levels' : jQuery('select[name=process_levels]').val(),
'process_method' : jQuery('select[name=process_method]').val(),
'process_name' : jQuery('input[name=process_name]').val(),
'process_msg' : jQuery('textarea[name=process_message]').val()
};
jQuery.post('display_array_processor.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">Done! Here is the response:</div><div>'+response.text+'</div>';
}
jQuery("#contact_results").hide().html(output).slideDown();
}, 'json');
});
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="form-style" id="contact_form" style="max-width:650px;">
<div id="contact_results"></div>
<br />
<div id="contact_body">
<h3>Simple Bootstrap jQuery Ajax Form</h3>
Levels:
<select name="process_levels" id="process_levels" class="input-sm form-control" />
<option value="noheaders">No Headers</option>
<option value="headers">With Headers</option>
<option value="">None</option>
</select>
Method:
<select name="process_method" id="process_method" class="input-sm form-control" />
<option value="commas">Commas</option>
<option value="tables">Tables</option>
<option value="">None</option>
</select>
<input type="submit" id="submit_btn" value="Submit" />
</div>
</div>
</body>
</html>
Here is a way to generate a table where values will be represented as comma-separated as soon as the data is considered more suitable for that.
Concretely, data will be represented as comma-separated if it is a non-nested, sequential array, so without named keys.
Here it is:
// Two generic utility functions:
function is_nested($array) {
return is_array($array) && count($array) < count($array, COUNT_RECURSIVE);
}
function is_assoc($array) {
return is_array($array) && array_keys($array) !== range(0, count($array) - 1);
}
function array_table_row($key, $row) {
$content = array_table($row);
return "<tr>\n<th>$key</th>\n<td>$content</td>\n</tr>\n";
}
function array_table($array) {
if (is_nested($array) || is_assoc($array)) {
$content = implode("", array_map('array_table_row', array_keys($array), $array));
return "<table border=1>\n<tbody>\n$content</tbody>\n</table>\n";
}
// At this point $array is too simple for a table format:
$color = is_array($array) ? "922" : "292";
$content = htmlspecialchars(is_array($array) ? implode(", ", $array) : $array);
return "<span style='color:#$color'>$content</span>";
}
See in eval.in
Output for the "headers" sample data:
Previous answer:
function array_csv($array) {
return is_array($array)
? "[" . implode(", ", array_map('array_csv', $array)) . "]"
: htmlspecialchars($array);
}
function array_table_row($index, $row) {
return "<tr>\n <th colspan='2'>Row ". ($index+1) . "</th>\n</tr>\n" .
implode("", array_map(function ($key, $value) {
return "<tr>\n <td>" . htmlspecialchars($key) . "</td>\n" .
" <td><span style='color:#" . (is_array($value) ? "ccf" : "cfc") . ";'>" .
array_csv($value) . "</span></td>\n</tr>\n";
}, array_keys($row), $row));
}
function array_table($array) {
return "<table border=1>\n<tbody>\n" .
implode("", array_map('array_table_row', array_keys($array), $array)) .
"</tbody>\n</table>\n";
}
echo array_table($myArray);
See it run on eval.in.
This is the output for the sample data:
<table border=1>
<tbody>
<tr>
<th colspan='2'>Row 1</th>
</tr>
<tr>
<td>Size</td>
<td><span style='color:#cfc;'>914 kB</span></td>
</tr>
<tr>
<td>Date</td>
<td><span style='color:#cfc;'>2015:02:08 18:01:00-08:00</span></td>
</tr>
<tr>
<td>Attributes</td>
<td><span style='color:#cfc;'>Regular; (none)</span></td>
</tr>
<tr>
<td>Names</td>
<td><span style='color:#ccf;'>[Alex Smith, Mike Jones]</span></td>
</tr>
<tr>
<td>Keywords</td>
<td><span style='color:#ccf;'>[2015, Alex, Mike, snowboarding, [A snow, B cold, C fun]]</span></td>
</tr>
<tr>
<td>Software</td>
<td><span style='color:#cfc;'>Invisible Space-Monkey Monitoring System 01</span></td>
</tr>
<tr>
<td>Duration</td>
<td><span style='color:#cfc;'>4800</span></td>
</tr>
</tbody>
</table>
It was not clear from your question what you want to do when arrays are nested deeper, going beyond the level of the comma-separated values.
With the above code, the comma-separated lists are wrapped in brackets, so it is clear where sub-arrays start and end within such lists.
Note that you should escape some characters of your data (like less-than and ampersand characters) with a function like htmlspecialchars.

Categories