I wrote some code to display a html table with PHP.
It reads data from a file and checks whether the value is true or false.
The problem is the ugly appearance of the table at the end of the function:
True False
blue
Red
Red
blue
I would like to display the table like this:
True False
blue Red
blue Red
Also it displays the outcome before the function is finished c.q flush();
Here is the code:
?>
<table>
<tr>
<th>True</th>
<th>False</th>
</tr>
<?php foreach ($trimmed_array as $value) { ?>
<tr>
<?php if (check($value) == 0) { ?>
<td><?php print $value ?></td>
<td> </td>
<?php
} else { ?>
<td> </td>
<td><?php print $value ?></td>
<?php
}
sleep(1);
ob_flush();
flush();
} ?>
</table>
I realize this code outputs the table like the first example but I can`t seem to figure out how to change it to fit the second example?
Your code creates one table row per item in the array, so there will always be one blank column per row.
In the 'table' that you would like to display, the items in each row aren't related to each other.
So really you're creating 2 lists here, not a table as such.
I'd do something like this
<?php
$all_values = array('true' => array(), 'false' = array());
foreach($trimmed_array as $value){
if (check($value) == 0){
$all_values['true'][] = $value;
}else{
$all_values['false'][] = $value;
}
}
foreach($all_values as $name => $values){
?>
<ul class="<?php print $name;?>">
<?php
foreach($values as $value){
?>
<li><?php print $value; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
You can then arrange your lists side by side with CSS
$true = array();
$false = array();
foreach ($trimmed_array as $value) {
if (check($value) == 0) {
$true[] = $value;
} else {
$false[] = $value;
}
}
for ($i = 0; $i < max(count($true), count($false)); $i++) {
echo '<tr>
<td>' . (isset($true[$i]) ? $true[$i] : '') . '</td>
<td>' . (isset($false[$i]) ? $false[$i] : '') . '</td>
</tr>';
}
Related
I have notification table on my database where the value is using like json.
Here's my table
id | touserid | data
1 2 a:1:{i:0;s:10:"INV-000001";}
2 2 a:1:{i:0;s:10:"INV-000003";}
3 2 a:1:{i:0;s:15:"The Mej Hotel";}
4 1 a:5:{i:0;s:28:"Total Goalsi:1;s:7:"6250000";}
5 1 a:1:{i:0;s:10:"INV-000007";}
I want to use that value in html table, but I don't know how to convert the value to html table in codeigniter
Here's my view code
<table class="table table-dark">
<tbody>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Data</th>
<
</tr>
</thead>
<tbody>
<?php foreach($notifications as $notif){ ?>
<tr>
<td><?php echo $notif['id'] ?></td>
<td><?php echo $notif['data'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's controller code
$this->db->limit($this->misc_model->get_notifications_limit(), $offset);
$this->db->where('touserid', get_staff_user_id());
$this->db->order_by('date', 'desc');
$data['notifications'] = $this->db->get(db_prefix() . 'notifications')->result_array();
$this->load->view('admin/sales/sales', $data);
But I don't see the data value get into html table like I want, in table it's show the error message " not_goal_message_failedArray"
I'm trying to encode the json, but I still don't know how to pass the json encode in controller to view in codeigniter
Here's the json encode
$page = $this->input->post('page');
$offset = ($page * $this->misc_model->get_notifications_limit());
$this->db->limit($this->misc_model->get_notifications_limit(), $offset);
$this->db->where('touserid', get_staff_user_id());
$this->db->order_by('date', 'desc');
$notifications = $this->db->get(db_prefix() . 'notifications')->result_array();
$i = 0;
foreach ($notifications as $notification) {
if (($notification['fromcompany'] == null && $notification['fromuserid'] != 0) || ($notification['fromcompany'] == null && $notification['fromclientid'] != 0)) {
if ($notification['fromuserid'] != 0) {
$notifications[$i]['profile_image'] = '<a href="' . admin_url('staff/profile/' . $notification['fromuserid']) . '">' . staff_profile_image($notification['fromuserid'], [
'staff-profile-image-small',
'img-circle',
'pull-left',
]) . '</a>';
} else {
$notifications[$i]['profile_image'] = '<a href="' . admin_url('clients/client/' . $notification['fromclientid']) . '">
<img class="client-profile-image-small img-circle pull-left" src="' . contact_profile_image_url($notification['fromclientid']) . '"></a>';
}
} else {
$notifications[$i]['profile_image'] = '';
$notifications[$i]['full_name'] = '';
}
$data = '';
if (!empty($notification['data'])) {
$data = unserialize($notification['data']);
$x = 0;
foreach ($data as $dt) {
if (strpos($dt, '<lang>') !== false) {
$lang = get_string_between($dt, '<lang>', '</lang>');
$temp = _l($lang);
if (strpos($temp, 'project_status_') !== false) {
$status = get_project_status_by_id(strafter($temp, 'project_status_'));
$temp = $status['name'];
}
$dt[$x] = $temp;
}
$x++;
}
}
$notifications[$i]['description'] = _l($notification['description'], $dt);
$notifications[$i]['date'] = time_ago($notification['date']);
$notifications[$i]['full_date'] = $notification['date'];
$i++;
}
echo json_encode($notifications);
Do you know where's my error when tried convert the json value in the table to html table code ?
Thank you
Your data in your table is looking like a serialised array
You will not get the data via echo, should use
$this->load->view("notification_view", $notifications);
instead of
echo json_encode($notifications);
I have the following code. How can I get my results ($x) for the foreach function to print into the table at the top, but in columns instead of a straight horizontal row? Is there a way to do this without just inserting each individual value into the HTML table? I need to do the same for my $employee['name'] variable but am not sure how I could get these values inserted into a table format without going one by one and entering the value myself.
Also, one value for $x at the end stays an integer and does not echo the string variable specified by the foreach function, is there a way I could fix this?
<!--4.3-->
<table>
<tr>
<td>Employee name</td><td></td><td></td><td></td><td></td><td></td>
<td>Type of Paying</td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td>
<td><?php echo $x;?></td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
</html>
<?php
foreach ($employees as $employee) {
$x = ($employee['wage'] * $employee['hrs']) * 4;
if ( 3000 <= $x ) {
echo "High paying";
} elseif (2000 <= $x && $x <= 2999) {
echo "Good paying";
} else {
echo "Low paying";
}
}
print_r ($x);
I inserted the foreach function into the table where I needed the results printed, then added tags within the ifelse statement after each parameter, and it worked like a charm.
My code for that table now looks like this:
<html>
<table>
<tr>
<td>Employee name</td><td></td><td></td><td></td><td></td><td></td>
<td>Type of Paying</td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td>
<td> <?php
foreach ($employees as $employee) {
$x = ($employee['wage'] * $employee['hrs']) * 4;
if ( 3000 <= $x ) {
echo "High paying"; echo "<br/>";
} elseif (2000 <= $x && $x <= 2999) {
echo "Good paying"; echo "<br/>";
} else {
echo "Low paying"; echo "<br/>";
}
} echo "<br/>" ; ?>
</td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
The other section above the foreach function will hold employee names and is not yet filled out to match.
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 }
} ?>
Couldn't find a specific answer to this so thought I'd ask. In short, I have a table that retrieves information from an API, based on data stored in my database and all I want to do is to get a total of certain, not all, columns from that table so that I can use them elsewhere on the site. As an example, let's use the Profit/Loss column and Total Divi. Do I have to somehow store the results as an array so that I can retrieve it elsewhere or is it something different?
<th>Profit/Loss</th>
<?php
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else
echo '0';
?></td>
<td><?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
}
?></td>
<td><?php
$firstno = floatval($vol[$x]);
$secondno = floatval($value['stats']['dividendRate']);
$sum = $firstno * $secondno;
print ($sum);
?></td>
</tr>
<?php } ?>
So I only left the profit/loss row/column as well as dividend amount (2nd column) and dividend total, just so you can see how I get these numbers in the first place.
Your requirement is, you want to use the profit/loss and total dividend column data of each row at the later stage of your code. What you can do is, create an empty array before the outermost for loop, and in each iteration of the loop, append the pair where key would be $x and value would be an array of profit/loss and total dividend column data.
<th>Profit/Loss</th>
<?php
$arr = array();
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
$arr[$x] = array('profitOrLoss' => $profitOrLoss, 'sum' => $sum);
}
?>
Update(1):
Based on your comment, all I want is to add up all the rows in Profit/Loss column together as well as rows in Total Divi column together. the solution code would be like this:
<th>Profit/Loss</th>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
$dividendRateSum += floatval($value['stats']['dividendRate']);
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
?>
Sidenote: If you want to see the complete array structure, do var_dump($arr);
I have an array such:
$prices = array();
Along with a MySQL query and fetch:
$query = "SELECT $columns FROM Prices WHERE `key` LIKE '$rows' LIKE '$AirportPU' AND rate LIKE '$rate'";
if($results = $db->query($query))
{
if($results->num_rows)
{
while($row = $results->fetch_object())
{
$prices[] = $row;
}
$results->free();
}
I've printed out the table using the following code: (I have removed some table columns)
<?php
if(!count($prices)) {
echo '<p>No results found for your current search. Use the inputs to the left to change the filters.</p>';
} else {
?>
<table>
<thead>
<tr>
<th>Location</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php
foreach ($prices as $p) {
?>
<tr>
<td> <?php echo $p->Location; ?> </td>
<td> £<?php echo $p->City; ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php } ?>
I can return data from the MySQL query, and print this to the table. However, sometimes not all the columns need be printed as they have no values. I would like to hide these columns.
I have tried checking the array using:
print (isset($prices["City"])) ? "Exists</br>" : "Doesn't Exist</br>" ;
But that always returns "Doesn't Exist"
if (array_key_exists("City",$prices))
{
echo "Element exists!";
}
else
{
echo "Element does not exist!";
}
That also returns false.
You need to check it inside the foreach loop which you are executing.
print (isset($p->City)) ? "Exists</br>" : "Doesn't Exist</br>" ;
Check with
if(empty($price['City'] || $price['City'] == "")){
//Hide column
}