Insert record to 3 columns from left to right - php

What is the best way to make that construction, i have many record with people names, and i need to put them all to 3 strips column, beetween each column huge space, and all names can be arbitrary length, for example
|Bob| |Jonh| |Victor|
|Sergej| |Kennedi| |Mark|
|Antuan| |Kristina| |Cryst|
I need to put them all to that colums in loop automaticaly, and one after the other,
|1| |2| |3|
|4| |5| |6|
|7| |8| |9|
Maybe somebody can advice me how it will be better to do, now i create 3 <ul> and in each ul i have some <li>, but that way will display my record one under the other. And if i use ul i need to get count all record, divide it to 3, and then put in each ul some record, maybe there is better way ?

As #Fabien pointed out, if its tabular data, then you can format it inside a table and use array_chunk() to group them by three's. Consider this example:
<?php
$names = array(
'Bob',
'John',
'Victor',
'Sergej',
'Kennedi',
'Mark',
'Antuan',
'Kristina',
'Cryst',
);
$names = array_chunk($names, 3); // group them by three's
?>
<table border="0" cellpadding="10">
<?php foreach($names as $key => $value): ?>
<tr>
<?php foreach($value as $index => $element): ?>
<td><?php echo $element; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

Related

Foreach table output rows near each other

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;?>

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; ?>

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;
}

how can put value in two columns?

how can a list of values that select of database, put in two columns together by PHP ?
EXAMPLE:
values select of database:
Internet
Game Notes
Internet
Pool
Coffee
Game Notes
i want like this:
Row-first order
<table>
<?php
$left = true;
foreach ($values as $value){
if ($left)
echo "<tr>";
echo "<td>$value</td>";
if (!$left)
echo "</tr>";
$left = !$left;
}
?>
</table>
With column-first order (as in your sample) you'll have to involve CSS and it's much complex. Something like
<div class='inline_div'>
<?php
$middle = count($values)/2+1;
$count = 0;
foreach ($values as $value){
if ($count==$middle)
echo "</div><div class='inline_div'>";
echo "$value<br/>";
++$count;
}
?>
</div>
inline_div is something like .inline_div {display:inline; float:left}. But that will definitely not work as expected, I'm no CSS master. IE does not support display:inline for sure.
If you want it exactly like you want in your example then you are going to have to read the whole table into memory, calculate the mid-point element and then build your table from that using a base point, an offset and a check to ensure that you've not repeated anything which involves a whole load of calculation.
A way around this would be to build two separate tables (each containing a single column) and then enclose them in a single table with two columns:
<?php
$list=array('a','b','c','d','e','f');
$midpoint=floor(count($list)/2);
$tableHeader='<table width="100%">';
$tableFooter='</table>';
$leftTable=$tableHeader;
$rightTable=$tableHeader;
for ($c=0; $c<$midpoint; $c++)
{
$leftTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$leftTable.=$tableFooter;
for ($c=$midpoint; $c<count($list); $c++)
{
$rightTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$rightTable.=$tableFooter;
$mainTable='<table><tr><td width="50%">'.$leftTable.'</td><td width="50%">'.$rightTable.'</td></tr></table>';
echo $mainTable;
?>
Or something along those lines. I haven't tested this code but it would be pretty close (may have to adjust the values in the "for" sections
The simple solution would be to use two divs. As a previous poster commented, you first need to count the elements. Suppose the items you want to display are in an array $items You can use this kind of code
<?php
$divItemCount = (count($items)%2) ? count($items)/2 + 1 : count($items)/2;
?>
<div id="leftdiv" style="width: 30%;">
<ul>
<?php
for($i=0; $i<$divItemCount; $i++) {
echo '<li>'. $items[$i] .'</li>';
}?>
</ul></div><div id="rightdiv" style="width: 30%; float:left"><ul>
<?php
for($j=$i; $j<count($items); $j++) {
echo '<li>'. $items[$j] .'</li>';
}?>
</ul></div>
I have not tested the code so there may be errors. You can use the border property in the divs to create a custom separator between the two lists.

How to implement DataList (asp.net) kind of functionality in PHP?

I want to display data in two columns as below
Entry 1 Entry 2
entry 1 description entry 2 description
Entry 3 Entry 4
entry 3 description entry 4 description
Entry 5
entry 5 description
Now In asp.net its prestty easy, just get a datalist make some settings and give data source to it and it will render it for you.
But in PHP how to display this kind of list, can anyone give me some code for this?
Thanks
i assume that you want draw an html table..
which is so easy to handle html layout & variable column number.
here is a sample code that will do exact what you need..
/* populate sample data */
for($i=1; $i<10; $i++) { $data_array[]=array('Entry '.$i,'entry '.$i.' description'); }
/* how many columns */
$column_number='3';
/* html table start */
?><table border="1" cellspacing="5" cellpadding="5"><?php
$recordcounter=1; /* counts the records while they are in loop */
foreach($data_array as $record) {
/* decide if there will be new Table row (<TR>) or not ... left of division by column number is the key */
if($recordcounter%$column_number==1){ echo "<tr>"; }
?>
<td>
<?=$record[0]?>
<br />
<?=$record[1]?>
</td>
<?php
/* decide if there will be end of table row */
if($recordcounter%$column_number==0){ echo "</tr>"; }
$recordcounter++; /* increment the counter */
}
if(($recordcounter%$column_number)!=1){ echo "</tr>"; }
?></table><?php
I suppose you're asking how to build the HTML output?
<?php $array = array('Item 1' => 'Description 1', 'Item 2' => 'Description 2'); ?>
<dl>
<?php foreach ($array as $item => $description) : ?>
<dt><?php echo $item; ?></dt>
<dd><?php echo $description; ?></dd>
<?php endforeach; ?>
</dl>
You can easily style this using CSS, floating them to make columns or what have you.
If you're using a framework it may include a helper of some sort to do this, but standard PHP does not.
Does that answer your question?

Categories