How to display associate arrays in a table php - php

Right i will start by showing you the code as it will make sense quickly
private static $cases = [
'100' => [
'id' => '1',
'case_no' => '1',
'name' => 'First Case'
],
'101' => [
'id' => '2',
'case_no' => '2',
'name' => 'Second Case'
],
];
Now i want a table with 3 columns and two rows.
The column headers should be id case_no and name.
foreach($results as $key => $value){
echo '<tr>';
echo "<td>";
echo
echo "</td>";
echo "<td>";
echo
echo "</td>";
echo "<td>";
echo
echo "</td>";
echo '</tr>';
}
what do i need to put in there to make this happen?
EDIT::
In my model i find a specific case by the $case_no someone searches for.
public static function findByCaseNo($case_no)
{
foreach (self::$cases as $case) {
if (strcasecmp($case['case_no'], $case_no) === 0) {
return new static($case);
}
}
return null;
}
Then my Controller send back to the view results as that specific case
return $this->render('search', [
'model' => $model,
'dataProvider' => $model->findAll(),
'results' => $case,
'case_no' => $case_no
]);

You either need two loops or call it key by key
echo "<table>";
foreach($cases as $key=> $value){
echo "<tr>";
echo "<td>".$value['id']."</td>";
echo "<td>".$value['case_no']."</td>";
echo "<td>".$value['name']."</td>";
echo "</tr>";
}
echo "</table>";

Related

Color table row based on variable value

I have a table which I fetch with jQuery from a database.
I would like to color each row based on one the value that a specific column has. Example I have column "status".
I want the row yellow if in that row the status is "progress".
I want the row red if in that row the status is "cancel"
I have tried with a class but that color the entire table,
I thought about using a variable color which will change the tr but not sure how to do that.
<style>
.yellow {
background-color: darkred;
}
</style>
<tbody>
<?php
include ('connection.php');
$sql = $link->query('SELECT * FROM job');
while($data = $sql->fetch_array()) {
echo '
<tr class="yellow">
<td>'.$data['id'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['date'].'</td>
<td>'.$data['device'].'</td>
<td>'.$data['model'].'</td>
<td>'.$data['problem'].'</td>
<td>'.$data['status'].'</td>
<td>'.$data['assigned'].'</td>
</tr>
';
}
?>
</tbody>
You could use inline style. I'm guessing that you have a 3rd status option of success, which will be green.
<?php
include ('connection.php');
$sql = $link->query('SELECT * FROM job');
while($data = $sql->fetch_array()) {
$color = $data['status'] == "cancel" ? "red" : ($data['status'] == "progress" ? "yellow" : "green");
echo '
<tr style="background-color:'.$color.'">
<td>'.$data['id'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['date'].'</td>
<td>'.$data['device'].'</td>
<td>'.$data['model'].'</td>
<td>'.$data['problem'].'</td>
<td>'.$data['status'].'</td>
<td>'.$data['assigned'].'</td>
</tr>
';
}
?>
A solution would be, to write the following in your css:
.bg-yellow {
background-color: yellow;
}
and than in PHP:
echo "<table>";
if ($data["status"] === ["expected_value"]) {
echo "<tr class='bg-yellow'>";
echo "<td>" . $data["status"] . "</td>"; // and so on
echo "</tr>";
} else {
echo "<tr>";
echo "<td>" . $data["status"] . "</td>"; // and so on
echo "</tr>";
}
echo "</table>";
I hope, it helps...
If you set the background color in your Style tag or CSS file it works global but you can use inline css like this here:
<?php
require('connection.php');
$sql = $link->query('SELECT * FROM job');
while($data = $sql->fetch_array()) {
if ($data['status'] == 'cancel') {
echo('<tr style="background-color:red">');
}
else {
if ($data['status'] == 'progress') {
echo('<tr style="background-color:yellow">');
}
else {
echo('<tr style="background-color:green">');
}
}
echo('
<td>'.$data['id'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['date'].'</td>
<td>'.$data['device'].'</td>
<td>'.$data['model'].'</td>
<td>'.$data['problem'].'</td>
<td>'.$data['status'].'</td>
<td>'.$data['assigned'].'</td>
</tr>
');
}
?>
or you gave an sepcial class to the row if the status is progress.
This is an example and I hope it helped you a bit.
My solution below is largely along the lines of what was posted earlier. However, doing it this way will give you a little more control over the semantics and color contrasts, when you want to take accessibility into account. You generally wouldn't want to pair 'black' with 'darkred' as your example seems to do. This code is also a little more concise.
<!DOCTYPE html>
<html>
<style>
td
{
padding: 0.5em;
}
.color-bg-green
{
background-color: green;
}
.color-bg-red
{
background-color: red;
}
.color-bg-yellow
{
background-color: yellow;
}
.color-bg-orange
{
background-color: orange;
}
.color-fg-white
{
color: white;
}
.color-fg-black
{
color: black;
}
</style>
<body>
<table>
<?php
$rowData = [];
$rowData[] =
['id' => 1, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'success', 'assigned' => 'Person A'];
$rowData[] =
['id' => 2, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'failure', 'assigned' => 'Person B'];
$rowData[] =
['id' => 3, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'success', 'assigned' => 'Person C'];
$rowData[] =
['id' => 4, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'pending', 'assigned' => 'Person D'];
$rowData[] =
['id' => 5, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'processing', 'assigned' => 'Person E'];
$rowData[] =
['id' => 6, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'success', 'assigned' => 'Person F'];
foreach ($rowData as $data)
{
switch ($data['status'])
{
case 'success':
{
$rowFgColor = 'white';
$rowBgColor = 'green';
}
break;
case 'failure':
{
$rowFgColor = 'black';
$rowBgColor = 'red';
}
break;
case 'pending':
{
$rowFgColor = 'black';
$rowBgColor = 'yellow';
}
break;
default:
case 'processing':
{
$rowFgColor = 'black';
$rowBgColor = 'orange';
}
break;
}
echo "<tr class=\"color-fg-$rowFgColor color-bg-$rowBgColor\">";
foreach (['id', 'number', 'date', 'device', 'model', 'problem', 'status', 'assigned'] as $column)
echo "<td>{$data[$column]}</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>

Codeigniter explode filename and return to view only gives one file

I have multiple files that have this name format field1_field2_field3.pdf. I separated each field and I want to return it to the view and paginate it. Can it be done? So far I have managed to explode the filename but only one file is returned to the view. Please help.
Controller :
$this->load->helper('directory');
$map = directory_map('./assets/data/');
$nric = $this->session->userdata('nric');
foreach($map as $row)
{
$separate = explode('_',$row);
}
$data['name'] = $separate[0];
$data['product'] = $separate[1];
$data['policyno'] = substr($separate[2],0,strlen($separate[2])-4);
$this->load->view('includes/user/header');
$this->load->view('user/statements',$data);
$this->load->view('includes/user/footer');
View
<tr>
<td><?php echo $name; ?></td>
<td><?php echo $product; ?></td>
<td><?php echo $policyno; ?></td>
</tr>
In your Controller you want the data array to contain multiple value so do something like this
EDIT: I am assuming that your $map variable is something like this (do a print_r if you want to see)
$map = [
'field1_field2_field3.pdf',
'field11_field22_field33.pdf',
'field111_field222_field333.pdf'
]
So using the loop
foreach($map as $row)
{
$separate = explode('_',$row);
$data[] = [
'name' => $separate[0],
'product' => $separate[1],
'policyno' => substr($separate[2],0,strlen($separate[2])-4)
];
}
Now doing as mentioned above in the foreach loop will give you $data like
$data = [
0 => [
'name' => 'field1',
'product' => 'field2',
'policyno' => 'field3',
],
1 => [
'name' => 'field11',
'product' => 'field22',
'policyno' => 'field33',
],
2 => [
'name' => 'field111',
'product' => 'field222',
'policyno' => 'field333',
],
]
this $data you can pass to your view, as you were doing
$this->load->view('user/statements',$data);
then in your view you can have something like
<table>
<?php foreach ($data as $dataRow):?>
<tr>
<td><?php echo $dataRow['name']?></td>
<td><?php echo $dataRow['product']?></td>
<td><?php echo $dataRow['policyno']?></td>
</tr>
<?php endforeach?>
</table>
I think this should work :)
Now use some fancy JavaScript plug-in and create a paginated view

How to unset foreach loop main array (the one is being iterated) inside the loop itself?

I have two foreach loops like below.
The idea is to process type 2 before type 1 in order. Code below works just fine but I was wondering how can I use unset to achieve same result instead of using another array $processed to keep track of what was processed.
I know that PHP foreach clones/copies the $data array for iteration. In other words, is it possible to unset type 2 from $data in second foreach loop and somehow first foreach loop skip them?
I know that PHP foreach clones/copies array for iteration.
$data = array(
array('type' => 1),
array('type' => 2),
array('type' => 2),
array('type' => 2),
array('type' => 1),
array('type' => 2),
array('type' => 2),
);
$processed = array();
foreach ($data as $firstKey => $firstValue) {
if (in_array($firstKey, $processed)) {
continue;
}
foreach ($data as $secondKey => $secondValue) {
if ($secondValue['type'] == 2) {
echo $secondValue['type'] . " processed " . "<br/>";
$processed[] = $secondKey; // can I use unset here?
}
}
echo $firstValue['type'] . " processed" . "<br/>";
}
Update
Hopefully with this update I can get my intention out.
Each child has a reference to its parent. All children need to be processed before its parent. Code below should work just fine. you can try it and the output of code below is the desired behavior. I would like to do it with unset if possible.
$data = array(
array('id' => 1, 'ref' => null, 'name' => 'parent 1'),
array('id' => 2, 'ref' => 1, 'name' => 'child 1'),
array('id' => 3, 'ref' => 1, 'name' => 'child 2'),
array('id' => 4, 'ref' => 1, 'name' => 'child 3'),
array('id' => 5, 'ref' => null, 'name' => 'parent 2'),
array('id' => 6, 'ref' => 5, 'name' => 'child 1'),
array('id' => 7, 'ref' => 5, 'name' => 'child 2'),
array('id' => 8, 'ref' => null, 'name' => 'parent 3'),
array('id' => 9, 'ref' => 8, 'name' => 'child 1'),
array('id' => 10, 'ref' => 8, 'name' => 'child 2'),
);
$processed = array();
foreach ($data as $ref => $firstValue) {
if (in_array($ref, $processed)) {
continue;
}
foreach ($data as $secondKey => $secondValue) {
if ($secondValue['ref'] == $firstValue['id']) {
echo $secondValue['id'] . "- " . $secondValue['name'] . " processed " . "<br/>";
$processed[] = $secondKey;
}
}
echo $firstValue['id'] . "- " . $firstValue['name'] . " processed" . "<br/>";
echo "<hr/>";
}
Code above output:
2- child 1 processed
3- child 2 processed
4- child 3 processed
1- parent 1 processed
6- child 1 processed
7- child 2 processed
5- parent 2 processed
9- child 1 processed
10- child 2 processed
8- parent 3 processed
Here's a simpler version that doesn't require unsetting anything. It just tests the type. For each type 1 entry, it processes all the type 2 entries first, then processes that type 1 entry.
<?php
$data = array(
array('type' => 1),
array('type' => 2),
array('type' => 2),
array('type' => 2),
array('type' => 1),
array('type' => 2),
array('type' => 2),
);
foreach ($data as $firstKey => $firstValue) {
if ($firstValue['type'] == 1) {
foreach ($data as $secondKey => $secondValue) {
if ($secondValue['type'] == 2) {
echo $secondValue['type'] . " processed " . "<br/>";
}
}
echo $firstValue['type'] . " processed" . "<br/>";
}
}
Another way to do this, that doesn't require testing the types in the inner loops, is simply to make two arrays: $dataType1 contains all the type 1 entries in $data, and $dataType2 contains all the type 2 entries. Then you just use simple nested loops:
foreach ($dataType1 as $firstValue) {
foreach ($dataType2 as $secondValue) {
echo $secondValue['type'] . " processed " . "<br/>";
}
echo $firstValue['type'] . " processed" . "<br/>";
}
Redoing my answer to match up with the OP's updated question.
Here is one method of achieving similar output using a recursive function
function processData(&$data, $ref = null)
{
foreach ($data as $key => $value) {
if ($ref !== null && $value['ref'] !== $ref) {
continue;
}
$data = processData($data, $value['id']);
echo $value['id'] . "- " . $value['name'] . " processed" . "<br/>";
unset($data[$key]);
}
return $data;
}
processData($data);
This function will modify your array though, constantly unsetting elements as it works through it.

cakephp2 can't display data from contain

I am developing a web app using cake php 2.
I have an issue while displaying data from 2 tables...
My models :
<?php
class Discipline extends AppModel{
public $hasMany = "Student";
}
?>
<?php
class Student extends AppModel{
public $belongsTo = array(
"Discipline" => array(
"className" => "Discipline",
"foreignKey" => "discipline_id"
)
);
}
?>
Here is my studentscontroller :
<?php
class StudentsController extends AppController{
function admin_index(){
if($this->request->is('put') || $this->request->is('post')){
$student = $this->request->data['Student'];
if($this->Student->save($this->request->data)){
$this->Session->setFlash("L'eleve a bien été modifié","notif");
}
}
$d['student'] = $this->Student->find('all',array(
'contain' => "Discipline"
));
$this->set($d);
}
}
I am trying to display student's data using this view :
<?php
foreach($student as $k => $v){
$v = current($v);
echo "<td>Action</td>";
echo "<td>Label</td>";
echo "<td>".$v['nom']." ".$v['prenom']."</td>";
echo "<td>".$v['sexe']."</td>";
echo "<td>".$v['naissance']."</td>";
echo "<td>".$v['Discipline']['designation']."</td>";
echo "<td>".$v['comite']."</td>";
echo "<td>".$v['classe']."</td>";
echo "<td>".$v['elite']."</td>";
echo "<td>".$v['alerte']."</td>";
echo "<td>".$v['quota1']."</td>";
echo "<td>".$v['quota2']."</td>";
echo "<td>".$v['total']."</td>";
echo "<td>Pris</td>";
echo "<td>Restant</td>";
echo "<td>Supp</td>";
}
?>
But i have an issue on this line :
echo "<td>".$v['Discipline']['designation']."</td>";
It says this error :
notice (8): Undefined index: designation [APP\View\Students\admin_index.ctp, line 47]
I am used to develop on cakephp 3 and I am pretty embarassed with that error.. what to do to display data from Disciplines table from my student view ?
Any idea ? Thx
EDIT: I did a debug on my StudentsController, and I found the data I wanna display :
array(
'student' => array(
(int) 0 => array(
'Student' => array(
'id' => '2',
'prenom' => 'Jean',
'nom' => 'Michel',
'sexe' => '1',
'naissance' => '2015-08-02',
'age' => '12',
'classe' => '1',
'discipline_id' => '1',
'comite' => 'test',
'categorie' => 'test',
'elite' => true,
'alerte' => 'test',
'quota1' => '12',
'quota2' => '12',
'total' => '24',
'note' => 'tete'
),
'Discipline' => array(
**'id' => '1',
'designation' => 'Alpin'**
)
)
)
)
i think you should change the view
Change:
foreach($student as $k => $value){
$v = current($value);
to:
foreach($student as $k => $v){
$v = current($v);
and change:
echo "<td>".$v['Discipline']['designation']."</td>";
to
echo "<td>".$value['Discipline']['designation']."</td>";
You overwrite the variable $v with the first found array, so $v would be $v['Student']
I for myself won't use current to go inside a array for CakePHP, but use $v['Student'] everywhere

CodeIgniter Multiple Row Update

I'm having a problem with a project of mine. I have read around and have no idea on what to do any more. This is a Codeigniter todo list project for our small office. I have made the displaying the contents of the database part already however I'm stumped on the updating part. On the view part, there's a todo list with checkboxes. If they are completed with the task, then they check the box and then put in the date when they did it and their initials. So they can check a lot of tasks and put dates and initials and I'm having a problem updating them in one time. I'm stumped. Please help. Thanks!
Controller
public function update_tasks() {
$this->load->model('model_members');
$post=$this->input->post();
$this->model_memberdashboard->reset_tasks($this->session->userdata('UserID')); // resets completion status of all tasks since checkboxes that are not checked doesn't do Post
foreach ($post['checkbox'] as $row){
$newData = array(
'completed'=> 1
);
$this->model_members->update_tasks($newData,$row);
}
$this->index();
Model
public function update_tasks($data,$id) {
$this->db->update("mastertaskslist",$data,['id' => $id]);
}
View <- Im using bootstrap so its a bit long
foreach ($allowedTasklist_1 as $row) {
echo '<li class="ui-state-default clearfix">';
echo '<div class=row>';
echo '<div class="col-sm-1">';
$checkbox=array(
'name' => 'checkbox[]',
'id' => 'checkbox[]',
'type' => 'checkbox',
'value' => $row->id,
'checked' => $row->completed,
);
if ($row->completed=="False"){
unset($checkbox['checked']);
}
echo form_checkbox($checkbox);
echo '</div>';
echo '<div class="col-sm-1">';
echo '<label>'.$num.'.'.'</label>';
echo '</div>';
echo '<div class="col-sm-10">';
echo '<div class="row">';
echo '<div class="col-sm-12">';
echo '<p>'.$row->taskTitle.'</p>';
echo '</div>';
echo '</div>';
echo '<div class="row">';
echo '<div class="col-sm-8">';
if ($row->lastUpdate=='0000-00-00'){
$currDate=NULL;
} else {
$currDate=date('m/d/Y', strtotime($row->lastUpdate));
}
$date=array(
'type' => 'text',
'class' => 'datepicker',
'name' => 'date['.$row->id.']',
'id' => 'date['.$row->id.']',
'value' => $currDate,
'placeholder' => 'mm/dd/yyyy',
'size' => '15'
);
echo form_input($date);
echo '</div>';
echo '<div class="col-sm-4">';
$initials=array(
'name' => 'initials['.$row->id.']',
'id' => 'initials[]',
'value' => $row->initials,
'maxlength' => '100',
'size' => '3',
);
echo form_input($initials);
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
$num++;
echo '</li>';
}

Categories