PHP: creating table with conditions - php

I have array like this in php:
$arr = [
[
"group": 1,
"name": John
],
[
"group": 1,
"name": Luke
],
[
"group": 1,
"name": Peter
],
[
"group": 2,
"name": Pia
]
]
expected output in html table:
GROUP | NAME
------|-----
| John
1 | Luke
| Peter
------|-----
2 | Pia
I attempted to work around the foreach but i cant figure it out. Below is the last code i tried:
<table>
<tr>
<th>GROUP</th>
<th>NAME</th>
</tr>
<tbody>
<?php $group = ''; ?>
<?php foreach($results AS $result) : ?>
<tr>
<td>
<?php if($group !== $result['group']): ?>
<?= $result['group'] ?>
<?php endif; ?>
</td>
<td>
<ul>
<li><?= $result['name'] ?></li>
</ul>
</td>
</tr>
<?php $group = $result['group']; ?>
<?php endforeach; ?>
</tbody>
</table>
but the result is:
GROUP | NAME
------|-----
1 | John
------|-----
| Luke
------|-----
| Peter
------|-----
2 | Pi
I need to show it as the about expected output.
Please help, thanks

You need to make group first like below
<?php
$results = [
["group"=> 1,"name"=> "John"],
["group"=> 1,"name"=> "Luke"],
["group"=> 1,"name"=> "Peter"],
["group"=> 2,"name"=> "Pia"]
];
$newArr = array();
foreach ($results as $key => $value) {
$newArr[$value["group"]][] = $value["name"];
}
?>
<table border="1">
<thead>
<tr><th>GROUP</th><th>NAME</th></tr>
</thead>
<tbody>
<?php foreach($newArr as $group=>$values){ ?>
<tr>
<td><?php echo $group;?></td>
<td>
<ul style="margin: 5px;">
<?php
foreach($values as $key=>$name){
echo "<li>$name</li>";
}
?>
</ul>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Which will give output,

All you need is a little counting and some CSS magic. Add the first block of code anywhere below your array and above your table.
$d = array();
foreach($results as $c){
if(array_key_exists($c['group'],$d)){
$d[$c['group']]++;
}else{
$d[$c['group']] = 1;
}
}
And then change your tbody code to this:
<tbody>
<?php $group = ''; ?>
<?php foreach($results AS $result) : ?>
<?php $t = $result['group']; ?>
<tr>
<?php if($group !== $result['group']): ?>
<?php echo '<td rowspan="' . $d[$t] . '" style="vertical-align:middle;">'; ?>
<?= $result['group'] ?>
</td>
<?php endif; ?>
<td>
<ul>
<li><?= $result['name'] ?></li>
</ul>
</td>
</tr>
<?php $group = $result['group']; ?>
<?php endforeach; ?>
</tbody>
Mind you this is just a mockup that should work but it's very basic and you'll properly need to beautify it a little.
Further more, you could remove the counting if you grouped your array's by "group" instead of having each person hold the group as well.

Related

I want to show position 1st, 2nd, 3rd in exam result

I Create a exam result sheet I want to show Positions all of student like 1st, 2nd, 3rd, .... like his percentage.
I want this result.
This is my code.
<table>
<thead>
<tr>
<th>Name</th>
<?php $total_sub = 0; ?>
<?php foreach ($subject as $sub): ?>
<?php if ($sub['sub_status']==1): ?>
<th colspan="2"> <center><?php echo $sub['sub_code']; ?></center></th>
<?php
$total_sub = $total_sub+1;
endif; ?>
<?php endforeach; ?>
<th colspan="2"><center> Total </center></th>
<th><center>Per% </center></th>
<th><center>Position</center></th>
<!-- onclick="sortTable(<?php echo $total_sub+2 ?>)" -->
</tr>
<tr>
<th>
</th>
<?php foreach ($subject as $sub): ?>
<?php if ($sub['sub_status']==1): ?>
<th> <center> OM </center></th>
<th> <center> TM </center> </th>
<?php endif; ?>
<?php endforeach; ?>
<th> <center> OM </center> </th>
<th> <center> TM </center> </th>
<th><center></center></th>
<th> <center> </center></th>
</tr>
</thead>
<tbody>
<?php foreach ($student as $std): ?>
<?php if ($std['enrolment_status']==1): ?>
<tr>
<?php
$total = 0;
$obtain = 0;
?>
<td>
<?php echo $std['student_registration_name'] ?>
</td>
<?php foreach ($subject as $sub): ?>
<?php if ($sub['sub_status']==1): ?>
<?php
$rt='N';
$rtt ='N';
$code = $std['en_id']."-".$sub['sub_id'];
foreach ($result as $res) {
$rest = $res['enrolment_en_id']."-".$res['subject_sub_id'];
if ($code === $rest) {
$rt = $res['er_obtain'];
$rtt = $res['er_total'];
$total = $total + $res['er_total'];
if ($rt == '-1') {
$obtain = $obtain + 0;
}else if($rt == '-2'){
$obtain = $obtain + 0;
}else {
$obtain = $obtain + $res['er_obtain'];
}
}
}
?>
<td><center><?php
if ($rt == '-1') {
echo "A";
}else if($rt == '-2'){
echo "-";
}else {
echo $rt;
}
?> </center></td>
<td><center><?php
if ($rt == '-1') {
echo "A";
}else if($rt == '-2'){
echo "-";
}else {
echo "$rtt";
}
?> </center></td>
<?php endif; ?>
<?php endforeach; ?>
<td><center><?php echo $obtain ?> </center></td>
<td><center><?php echo $total ?> </center></td>
<td>
<center>
<?php
if ($total!=0) {
$per = $obtain/$total*100;
echo number_format($per, 1);
echo " %";
}else {
echo "0 %";
}
?>
</center>
</td>
<td>
<center>
</center>
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
I'm trying to get the ranking position of a student by percentage. For example if student 1 has 90.0% with a total of 100 points and student 2 has 80.5% with a total of 100 points. Student 1 will ranking position higher than student 2. I was wondering how would I be able to do this?
You can use array_multisort,array_walk to rank the records. For example
$records = [
0 => ['percentage' => 95],
1 => ['percentage' => 91],
2 => ['percentage' => 98],
3 => ['percentage' => 70]
];
array_multisort(array_column($records, 'percentage'),SORT_DESC,$records);
array_walk($records, function(&$v,$k){
$v['rank'] = $k + 1;
});
echo '<pre>';
print_r($records);
Output
Array
(
[0] => Array
(
[percentage] => 98
[rank] => 1
)
[1] => Array
(
[percentage] => 95
[rank] => 2
)
[2] => Array
(
[percentage] => 91
[rank] => 3
)
[3] => Array
(
[percentage] => 70
[rank] => 4
)
)
have a look at this, it is a way to do all the work in mysql so you can just echo out the array - also it takes into account ties https://www.oreilly.com/library/view/mysql-cookbook/0596001452/ch13s10.html

How to fetch data in table group by other column in PHP

I have a record like this in database:
section_id description level_id
1 Amethyst 1
2 Betelguise 1
3 Daisy 2
4 Rose 2
I want it to display in my php table just like this:
Level 1
Amethyst
Betelguise
Level 2
Daisy
Rose
Can anyone please help me? I am new at this.
Here's my code:
<table>
<thead>
<tr>
<th>Descriptions</th>
<th>Level</th>
</tr>
</thead>
<?php $sql = "SELECT * FROM tbl_sectiontaken"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while($row = $result->fetch_assoc()) { ?>
<?php $id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id']; ?>
<tbody>
<tr>
<td style="text-transform:capitalized;">
<?php echo $desc; ?>
</td>
<td style="text-transform:capitalized;">
<?php echo $gr; ?>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
But it gives me this result in table:
Descriptions Level
Amethyst 1
Betelguise 1
Daisy 2
Rose 2
You can use group_concat function for this. Use below code if suits your requirements
<?php $sql = "SELECT level_id,GROUP_CONCAT(description) AS description FROM series group by level_id"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while ($row = $result->fetch_assoc()) { ?>
<?php
$id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id'];
$leveArr[$gr][] = $desc;// Create an array with level and description
} } ?>
</tbody>
<table>
<tr><!-- header-->
<?php foreach ($leveArr as $key => $value) { ?>
<td><?php echo "LEVEL " . $key ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($leveArr as $key => $value) {
foreach ($value as $key_1 => $data) { ?>
<td><?php
$data = explode(",", $data);
foreach ($data as $key_2 => $final) {
echo $final . "<br>";
}
?></td>
<?php }
} ?>
</tr>
</table>
Updated
Check the sandbox example
Change query with GROUP_CONCAT
SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id
And After.They return array like this
$arr=[['description'=>'a,b,c,d','level_id'=>'1','heigher'=>'4'],['description'=>'a,b,c,d','level_id'=>'2','heigher'=>'4']]; ?>
Then Finally Create Table as like this
$sql="SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id";
$result = $conn->query($sql);
$arr =[];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$arr[]=$row;
}
}
<table>
<thead>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?='level'.$value['level_id']?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
$arr = array_filter($arr,function($a=[]){
return $a['level_id'] != 0
}) //filter level not a zero
$h = max(array_map(function($a=[]){
return $a['heigher']; //filter array['heigher only']
},$arr)); // its get the heighest length of description value like [10,15,100]=>100
foreach ($arr as $key => $value){
$value['description'] = !empty($value['description']) ?explode(',',$value['description']):'';
$arr[$key]=$value;
}
?>
<?php for ($i=0; $i < $h[0]; $i++) {?>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?=isset($value['description'][$i])? $value['description'][$i] :''?></th>
<?php endforeach; ?>
</tr>
<?php }?>
</tbody>
</table>

Codeigniter explode to html table

I'm currently having issue explode to html table.
My Controller
public function idp_test()
{
$this->load->model('groups/groups_model');
$scholar_id = $this->session->userdata('scholar_id');
$groups = $this->groups_model->retrieve_groups_idp($this->scholar->level_id);
$content = array(
'groups' => $groups,
'scholar' => $this->scholar,
'page_title' => 'My individual development plan',
'page_view' => 'scholar/activities/idp_test',
'page_scripts_view' => 'scholar/inc/_choose_activities_scripts',
'sidebar_menu' => 'idp test'
);
$this->load->view("theme/base", $content);
}
My Model
public function retrieve_groups_idp($level_id)
{
$this->db->select("groups.*, levels.name as levelname");
$this->db->join('activities', 'groups.activity_ids = activities.activity_id' );
$this->db->join('levels', 'levels.level_id = groups.level_id', 'left' );
$this->db->join('activity_types', 'activities.activity_type_id = activity_types.activity_type_id', 'left' );
$this->db->where('groups.level_id', $level_id);
$this->db->group_by('groups_name');
$this->db->order_by('groups_name');
$qr = $this->db->get('groups');
return $qr->result();
}
public function retrieve_activity_desc($activity_ids)
{
$activity_desc_arr[] = explode(', ', $activity_ids);
foreach ($activity_desc_arr as $activity_id){
$this->db->select("activity_id as activityid, CONCAT(activities.name, ' - ', activity_types.name) AS description", FALSE);
$this->db->join('activity_types', 'activities.activity_type_id = activity_types.activity_type_id');
$this->db->where_in('activities.activity_id', $activity_id);
$qr = $this->db->get('activities');
return $qr->result();
}
}
My View
<?php foreach ($groups as $groups): ?>
<table class="table table-vcenter">
<thead>
<tr class="active">
<th><?php echo $groups->groups_name?></th> <!--Series Header -->
<th class="text-center"><small><strong>Module Type</strong></small></th>
<th class="text-center"><small><strong>Status</strong></small></th>
<th class="text-center"><small><strong>Action</strong></small></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php
$rows = $this->groups_model->retrieve_activity_desc($groups->activity_ids);
foreach ($rows as $row){
echo var_dump($row->description);
}
?></td>
<td class="text-center">belom lagi</td>
<td class="text-center">TO ATTEND</td>
<td class="text-center">View Session</td>
</tr>
</tbody>
</table>
<?php endforeach ?>
i can't post images, so below are some sample in view so far
SERIES 1 FOR FS | MODULE TYPES | STATUS | ACTION
Series 1 - FILSeries 1 - CBLSeries 1 - PEL | belom lagi | to attend |
and what i need to achieve is like below sample in view
SERIES 1 FOR FS | MODULE TYPES | STATUS | ACTION
Series 1 - FIL | belom lagi | to attend |
Series 1 - CBL | belom lagi | to attend |
Series 1 - PEL | belom lagi | to attend |
I'm newbie with php & codeigniter, sorry with my english.
Thanks
Think about what you have in your view code:
<tr>
<td><?php
foreach($rows as $row){
var_dump($row->description);
}
?>
</td>
<td>belom lagi</td>
<td>to attend</td>
</tr>
Of course this will all be printed into one table cell, how it could produce anything else, right?
What you need is something like this:
<?php
foreach($rows as $row){
echo "<tr>"; // you need a new row for every entry
echo "<td>".$row->description."</td>";
echo "<td>belom lagi</td>";
echo "<td>to attend</td>";
echo "</tr>";
}
?>
After a few studies, i figured it out, just want to share with everybody.
EDITED - Controller
public function idp_test()
{
$this->load->model('groups/groups_model');
$this->load->model('activities/activity_type_model');
$scholar_id = $this->session->userdata('scholar_id');
$groups = $this->groups_model->retrieve_groups_idp($this->scholar->level_id);
foreach ($groups as $group) {
$act_desc = $this->groups_model->retrieve_activity_desc($group->activity_ids);
$group->activity_ids = $act_desc;
}
EDITED - View
<!-- START TABLE HEADER -->
<?php foreach ($groups as $group): ?>
<table class="table table-vcenter">
<thead>
<tr class="active">
<th><?php echo $group->groups_name?></th> <!--Series Header -->
<th class="text-center"><small><strong>Module Type</strong></small></th>
<th class="text-center"><small><strong>Status</strong></small></th>
<th class="text-center"><small><strong>Action</strong></small></th>
</tr>
</thead>
<tbody>
<?php foreach ($group->activity_ids as $session): ?>
<tr>
<td><?php echo $session->description; ?></td>
<td class="text-center"><?php echo $session->modulename; ?></td>
<td class="text-center">STATUS</td>
<td class="text-center">View Session</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endforeach ?>
<!-- END 1 -->
Come out as what i need.
Thank you stackoverflow.

PHP nesting foreach in table

I can't seem to get my table to have the right output. The code is the following:
<div class="bubbleTitle">Spetsialistide tööaeg graafiku alusel</div>
<table style="width: 600px" class="slicedTable">
<tr>
<th>Spetsialist</th>
<th>Tunnid</th>
</tr>
<tr>
<?php foreach($specs as $specName => $spec): ?>
<td><?php echo $specName?></td>
<?php foreach($tunnid as $tund): ?>
<td><?php echo $tund?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
I have tried everything in this thread: Nested Loop in table PHP , but none of that has worked either
The output is the following:
name - value
value2
value3
name2 - value
value2
value3
etc.
I would like it to be:
name1 - value1
name 2 - value2 etc.
Where $tunnid comes from:
result = mysql_query("SELECT `worker_id`, SUM(TIMESTAMPDIFF(HOUR, `start`, `end`)) as `total` FROM
`spa_worker_times` WHERE (`start` BETWEEN '".$validated['start']."' AND '".$validated['end']."') AND
(`end` BETWEEN '".$validated['start']."' AND '".$validated['end']."') GROUP BY `worker_id`") or die(mysql_error());
$tunnid = array();
while ($row = mysql_fetch_assoc($result)) {
$tunnid[] = $row['total'];
Where specs come from:
$data = $this->BookingProcedures->query("SELECT AProcedure.name, BookingGroup.booking_package_id > 0 AS pack_proc," .
"SUM(BookingProcedure.price) AS price, Worker.name, COUNT(BookingProcedure.id) AS num" .
" FROM spa_booking_procedure_specialists BookingProcedureSpecialist, " .
"spa_booking_procedures BookingProcedure, " .
"spa_booking_groups BookingGroup, spa_procedures AProcedure, spa_workers Worker" .
" WHERE !BookingProcedure.deleted" .
" AND DATE(BookingProcedure.start) >= '".$validated['start']."'" .
" AND DATE(BookingProcedure.start) <= '".$validated['end']."'" .
" AND BookingProcedureSpecialist.booking_procedure_id = BookingProcedure.id" .
" AND Worker.id = BookingProcedureSpecialist.specialist_id" .
" AND BookingGroup.id = BookingProcedure.group_id" .
" AND AProcedure.id = BookingGroup.procedure_id" .
" GROUP BY AProcedure.name, BookingGroup.booking_package_id > 0, Worker.name");
<div class="bubbleTitle">Spetsialistide tööaeg graafiku alusel</div>
<table style="width: 600px" class="slicedTable">
<tr>
<th>Spetsialist</th>
<th>Tunnid</th>
</tr>
<tr>
<?php foreach($specs as $specName => $spec): ?>
<td><h2><?php echo $specName?></h2>
<table><tr>
<?php foreach($tunnid as $tund): ?>
<td><?php echo $tund?></td>
<?php endforeach; ?>
</tr></table></td>
<?php endforeach; ?>
</tr>
</table>
This will output like this
Name1
value1 | value2 | value3
Name2
value1 | value2 | value3
<?php foreach($specs as $specName => $spec) { ?>
<tr>
<td><?php echo $specName?></td>
<?php foreach($tunnid as $tund) { ?>
<td><?php echo $tund?></td>
<?php } ?>
</tr>
<?php } ?>
will result in
name value value value
name value
name value value
and so on
Where does $tunnid come from. I would assume it contains only values, but in which way, are they in a regular array or an associative? My code would work if $tunnid contains the values to one name. But i assume that is not the case!?
<table style="width: 600px" class="slicedTable">
<tr>
<th>Spetsialist</th>
<th>Tunnid</th>
</tr>
<tr>
<?php foreach($specs as $specName => $spec): ?>
<td><?php echo $specName?></td>
<!-- seperate with anything -->
<td><?php echo implode(',', $tunnid); ?></td>
<?php endforeach; ?>
</tr>
</table>
<?php
$i = 0;
foreach($specs as $specName => $spec){
?>
<tr>
<td><?php echo $specName?></td>
<td><?php echo $tunid[$i++]; ?></td>
</tr>
}
?>

How to get several data from a form?

I have two added form. In the first, I choose one client and for him I add several domains names.
Then, when I clik to next, I arrived on a second form in which there are the several domains names (I added before ) in each row with others fields for each one (registar, url and remark). It seems to like this :
toto.com | Directnic | www.toto.com | blablabla
toto.fr | Afnic | www.toto.fr | bla
toto.net | Gandi | www.toto.net | blabla
But when I want to recover this data into my action to add them into my database, I get only the last line. Why ?
My form :
<form action="<?php echo url_for('#add_domaines');?>" method="post">
<?php echo $form->renderGlobalErrors() ?>
<table class="form_add_domaines">
<thead>
<tr>
<th><?php echo $form['nom_domaine']->renderLabel()?></th>
<th><?php echo $form['compte_registar_id']->renderLabel() ?></th>
<th><?php echo $form['url']->renderLabel() ?></th>
<th><?php echo $form['remarque']->renderLabel() ?></th>
</tr>
</thead>
<tbody>
<?php
$domaines = explode("\n",$add_domaines);
for($i=0; $i<count($domaines); $i++)
{?>
<tr>
<td>
<?php
if(1==strcmp(' ', $domaines[$i]))
{
echo "<span style='color:red;'>"."<b>Warning, missing domain name.</b>"."</span>";
}
else
{
echo $domaines[$i];
}
?>
</td>
<td>
<?php echo $form['compte_registar_id']->renderError() ?>
<?php echo $form['compte_registar_id'] ?>
</td>
<td>
<?php echo $form['url']->renderError() ?>
<?php echo $form['url'] ?>
</td>
<td>
<?php echo $form['remarque']->renderError() ?>
<?php echo $form['remarque'] ?>
</td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<td>
<?php echo link_to(__('Back', array(), 'sf_admin'), '#domaine_new') ?>
</td>
<td>
<?php echo $form->renderHiddenFields(false) ?>
<input type="submit" class="submit" value="Add" />
</td>
</tr>
</tfoot>
</table>
</form>
My action :
[...]
$this->form = new AddDomainesForm();
$this->form->setDefault('client_id', $idClient);
$this->form->setDefault('nom_domaine', $noms_domaine);
if($request->isMethod('post'))
{
$name = $this->form->getName();
$values = $request->getParameter($name);
$files = $request->getFiles($name);
$this->form->bind($values, $files);
if($this->form->isValid())
{
print_r($values);break;
//$this->form->save();
$this->getUser()->setFlash('notice', 'OK.');
$this->redirect('#domaine');
}
}
print_r($values) return only the last row of my form
Array ( [compte_registar_id] => 1 [url] => www.toto.net [remarque] => blabla [nom_domaine] => toto.com toto.fr toto.net [client_id] => 17 [_csrf_token] => ... )
Thank you !
When multiple form elements have the same name, only the last one will be taken.
Did you see that cou can send arrays directly?
<inut type="text" name="foobarlist[]">
<inut type="text" name="foobarlist[]">
<inut type="text" name="foobarlist[]">
$_GET['foobarlist'] will return an array with 3 elements.
The brackets are the key.

Categories