Foreach table output rows near each other - php

I have json html table in php, now i can't get it work that the output in the table will be near each other.
I am already few days busy with this, hope some one can help me.
<?php foreach($data2 as $row): ?>
<tr>
<td><?=$row['model'];?></td>
<td><?=$row['model2'];?></td>
</tr>
<?php endforeach;?>
My json output:

It looks like the JSON is not formatted for what you are trying to do. Every object has either modal or modal2, so the one that is not filled is undefined.
You should get the length of the longest list and use a normal for loop.
<?php ($index = 0; $index <= $lengthOfLongestList; $index++): ?>
<tr>
<td><?=$data2[index]['model'];?></td>
<td><?=$data2[index]['model2'];?></td>
</tr>
<?php endforeach;?>

Related

Pass a parameter to a method using PHP custom MVC

Im using a custom MVC in PHP
I have two tables.
Controles and professors
professors table contains an id of course --> id_professor
controles table contains a field called --> id_professors in which I store a list of profs ids this way ==> 1;2;5;9
In my datatable Im retrieving a list of controles from controles table
for the Model, Im using this class
public function fetchControlesListe(){
stmt = $this->db->prepare("SELECT * FROM controles ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
return $stmt->fetchAll();
}
Controller
liste_controles.php
class Liste_Controles extends Controller {
function __construct(){
parent::__construct();
}
$this->view->fetchCtrlListe= $this->model->fetchControlesListe();
$this->view->render('liste_controles/index');
}
VIEW
<table>
<thead>
<tr>
<th>N°</th>
<th>Module</th>
<th>Salle</th>
<th>Surveillants</th>
</tr>
</thead>
<tbody>
<?php foreach($this->fetchCtrlListe AS $key=>$value): ?>
<tr>
<td><?php echo $controle['id_controle']; ?></td>
<td><?php echo $controle['intitule_module']; ?></td> <
<td><?php echo $controle['intitule_salle'];?></td>
<td>
<?php foreach($this->prof as $profs): ?>
HERE, I would like to retrieve the list of profs from professors
table and the field id_profs in professors table stores an
array, as i said before, containing a list of ids (Ex: 1;2;3;4;5)
I would like to loop through that array and retrieve the name of
professor from professors table if the id_professor Exists in that array
. I know I have to create another METHOD but The PROBLEM is i don't know how to pass parameters in the method and call it from the controller to pass it to the view . and the param would be $controle['id_professor']
<?php endforeach; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
The result would be like this:
EDIT:
I know that is not a good idea to store lots of ids as an array, but
my question I just want to know how to do a foreach loop inside
another foreach loop using another method with a paramater that will
be passed from the first loop
There isn't one solution but what you can do is, because you know that id_professors is a string composed of ids separated by commas, you can retrieve an array of identifiers this way :
$ids = explode(",", $profs[id_professors']);
and then
<?php foreach($this->prof as $profs): ?>
<?php $ids = explode(",", $profs['id_professors']); ?>
<?php foreach($ids as $id): ?>
//DO STUFF with $id
<?php endforeach; ?>
<?php endforeach; ?>
Notice that the entire thing is not very beautiful because of opening/closing php tags constantly but I hope you'll make a wonderful templates system for your MVC framework :)
From there, it would not be that nice to access the database directly from the view so a better (not perfect) solution would be to provide the view an array made of professors like this one :
$this->view->profs_list = array(
1 => "Prof 1",
2 => "Prof 2",
//etc.
);
with the key of the array being the profs' identifier.
Then you can retrieve their name through the loop :
<?php foreach($this->prof as $profs): ?>
<?php $ids = explode(",", $profs['id_professors']); ?>
<?php foreach($ids as $id): ?>
<span><?php echo $this->profs_list[$id]; ?></span><br />
<?php endforeach; ?>
<?php endforeach; ?>

php echo not working in html

This is my first code in php, so my problem might be so obvious. sorry if it is so easy :)
What I'm trying to do is that I am selecting some rows from my data base using
$rrows = Select ( "*" , $tbl_SubForum , null, "p");
$rrows->setFetchMode(PDO::FETCH_CLASS, 'subForum');
I know this works fine.
Each row has the description of a sub forum, containing title and id. I am trying to show sub forum titles in table cells using this code:
<table cellpadding=50px cellspacing=20px BORDER=0>
<?php
$i=0;
while($rrow = $rrows->fetch()){
var_dump($rrow);
?>
<tr>
<td class='subforum' id='subforum1'>
<?php echo $rrow["title"]; ?><br>
Sub forum manager<br>
Posts: 200<br>
Active users: 50<br>
</td>
</tr>
<?php
$i++;
}
?>
the line echo $rrow["title"]; doesn't work and so the page is empty, except for the result of the first var_dump
First var_dump of the first $rrow shows:
as you can see, there actually is a title field in the array and there is only one var_dump so the while loop doesn't work anymore!
why is this happening?
Because $rrow is an object rather than an array, you have to use $rrow->title to access its data member.

convert the result set foreach to for loop in php

I am doing a project in codeigniter.Here I want to fetch the fields time and url to view.I want to show something like this
The first field is time and second one is url.I used the following code to fetch the value
foreach ($path as $row) {
?>
<tr>
<td>
<a href="#">
<div class="span6 pull-left"><?php echo $row->time;</div>
<div class="span3 pull-left"><?php echo $row->url ?></div>
</a>
</td>
</tr>
<?php
}
?>
But actually the first row of time is the difference between the time on first row and the second row.And the time on second row is the difference between time on second row and third row so on.I have tried with foreach loop.But I didnt get any idea to implement this.Anyone help me for converting this foreach loop to for loop to accomplish the task.
Thanks in advance.
maybe something like..
for( $i = 0 ; $i < count($path) ; $i++ ) {
$time = $path[$i]->time - $path[$i+1]->time;
}
be aware issue with last index..

How to get only one result from foreach(PHP)

The code loop an array and display all views for a user. Now things changed and I just need to display one result from a foreach loop. How do I do that?
<table class="report_edits_table">
<thead>
<tr class="dates_row">
<?php foreach($report['edits'] as $report_edit) : ?>
<td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
<?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
<span class="ui-icon ui-icon-trash">Remove</span>
<?php endif?>
<?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach($report['edits_titles'] as $index => $title) : ?>
<tr class="coach_row">
<?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
<td class="name_column"><?php echo $title ?></td>
<td class="value_column"><?php echo $report_edit[$index] ?></td>
<?php endfor ?>
</tr>
<?php endforeach ?>
</tbody>
Use the break command for simple conversion:
<?php for ... ?>
... stuff here ...
<?php break; ?>
<?php endfor ... ?>
A better solution would be to remove the foreach completely.
It sounds like you want to grab the first element from an array without having to loop through the rest of them.
PHP provides a set of functions for situations like this.
To get the first element in an array, start off using the reset() function to position the array pointer to the start of the array, then use the current() function to read the element that the pointer is looking at.
So your code would look like this:
<?php
reset($report['edits']);
$report_edit = current($report['edits']);
?>
Now you can work with $report_edits without having to use a foreach() loop.
(note that the array pointer does actually start by default at the first record, so you could skip the reset() call, but it's best practice not to do that because it might have been changed elsewhere in your code without you realising it)
If you want to move on to the next record after that, you can use the next() function. As you can see, if you wanted to, it would theoretically be possible to use these functions to write an alternative type of foreach() loop. There wouldn't be any point in using them them that way, but it's possible. But they do allow more fine-grained control over the array, which is handy for situations like yours.
Hope that helps.
Plenty of ways
Access the index of the array element in question directly
Update whatever logic fetches/generates the array to only return the element of interest
Use a for loop that terminates after a single loop
array_filter your array to get the element of interest
Break at the end of your foreach loop so it terminates after the first iteration
Conditionally check your index in the foreach loop and only output markup if the index matches the element of interest
And so on
I'd recommend just getting the array element of interest (number 2 on the list) as it means less data bouncing around your code (and probably between your PHP box and the database if you're populating the array from an SQL server)
Simplest method?
Place a break as the last line of your foreach. It'll execute once, then quit. (As long as which element you stop on is of no importance).
Secondary method: use array_pop or array_shift on your $report['edits'] or $report['edits_titles'] to get on element, lose the for loop, and reference the element you just retrieved.
For example:
//
// current
//
foreach ($report['edits'] as $report_edit) :
/* markup */
endforeach;
//
// modified version
//
$report_edit = array_shift($report['edits']);
/* markup */
Use <?php break ?> before <?php endforeach ?>
example ::
<?php
foreach ($this->oFuelData AS $aFuelData ) {
echo $aFuelData['vehicle'];
break;
}
?>
You can also use it for reference
foreach($array as $element) {
if ($element === reset($array))
echo $element;
if ($element === end($array))
echo $element;
}

sql, php, html table question

I want to grab data from a mysql database by using php. The data looks something like this:
apple 3
orange 2
banana 4
I want to take the data and put it in a html table and use css to make it look pretty, but I dont want to deal with it inside <?php ?>
After I grab the
$result = mysql_query("SELECT * FROM Table");
can I reference the result variable outside the <? php ?> tags?
No. PHP can only be done in <?php ... ?> or <?= ... ?>. Use a template engine such as Smarty if you want substitution in this manner.
in short, no you cant, it is a php variable (technically a resource in this case) so you have to parse it through the php engine, which requires the php tags
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fruit'].'</td><td>'.$row['id'].'</td></tr>';
}
echo '</table>';
Short answer is no. HTML cannot deal with dynamic content.
If you want to cut down the amount of echo statements within your code you can store the html within a given variable and then make reference to it.
I find it better to do the following:
<table>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row['fruit']?></td>
<td><?php echo $row['id']?></td>
</tr>
<?php endforeach; ?>
</table>
This provides clarity and minimizes concatenation.

Categories