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.
Related
i have more then 5 link for image, so i want to make like this,
$p_image1, $p_image2, $p_image3, $p_image4, $p_image5
but i dont understand why my cod is not work...
this is my code for get array data:
$id = mysqli_real_escape_string($koneksi,$_GET['i']);
$query = mysqli_query($koneksi,"SELECT * FROM `tb_produk` WHERE `p_id` = '$id'");
$get = mysqli_fetch_array($query);
this is my code for loop:
if ($j_image > 1) {
for ($i = 1; $i <= $j_image; $i++) {
$p_image[] = $get['p_image'.$i];
if ($i > 4) {
break;
}
?>
<li data-uk-slideshow-item="<?php echo $i ?>">
<img src="<?php echo $get['p_image'.$i]; ?>">
</li>
<?php
}
}
?>
why this is not work, thanks for your help before :)
I think creating dynamic named variables is just a way to make things harder than it is.
Instead I believe fixing the problem is the solution.
Dynamic variables is just harder to work with than arrays and will make bugs in your code some day.
Here I use a foreach on the $get array which means it will loop the items there is and we don't have to count and guess stuff.
Then I removed this new array you created as I don't see the point of it and instead go directly to the output part with my foreach variable $image.
I also keep the code in PHP and echo the html as I find that easier to read, but that is purely opinion and you can do whichever you want.
$i=1;
foreach($get as $image){
if ($i > 4) {
break;
}
echo "<li data-uk-slideshow-item=" . $i .">\n";
echo ' <img src="' . $image . '">' . "\n";
echo "</li>\n";
$i++;
}
Example output:
<li data-uk-slideshow-item=1>
<img src="1">
</li>
<li data-uk-slideshow-item=2>
<img src="2">
</li>
<li data-uk-slideshow-item=3>
<img src="3">
</li>
<li data-uk-slideshow-item=4>
<img src="4">
</li>
Not sure if your code is supposed to output four or five items.
But I just left the if and break as it was in your code.
https://3v4l.org/MrAng
Array is the perfect way to handle multiple similar values. You should really not consider making separate variables for this.
Still, in order to create dynamic variables, you need to use an additional $, and wrap them in curly braces {..}:
for ($i = 1; $i <= $j_image; $i++) {
// Create string for dynamic variable name and put it inside curly braces
// use $ in front to define this as a new variable
${'p_image'.$i} = $get['p_image'.$i];
if ($i > 4) {
break;
}
I'm listing some movies in my web so the user can choose the best movie.
I’m classifying them by genre.
But the lists under each genre are too long and I want to make two columns of titles.
The number of movies in each column will depend of the genre.
So my code is like this now:
$i = 1;
echo "<ul>";
foreach($arrayMovies as $k=>$v)
{
echo "<li><input type=\"checkbox\" id=\"flat-$i\" name=\"$genre-$i\" value=\"$k\">
<label for=\"flat-$i\">$v</label></li>";
$i++;
}
echo "</ul>";
This code is showing the long list, something like this for drama:
Forest Gump
The Hours
Mullholand Drive
Titanic
.
.
Let’s say that for the drama genre I need two titles per column:
<ul>
<li> Forest Gump</li>
<li> The Hours</li>
</ul>
<ul>
<li> Mullholand Drive</li>
<li> Titanic</li>
</ul>
How can achieve this with my code??
The second column I can achieve by using css, I just need a new <ul> after two titles.
Please notice that the number two in -two titles per column- is a dynamic number*
*I’ll count how many rows per title each genre has to get a total number and then I’ll do half of it to get the number of titles per column (the number of titles in each genre is even)
Thanks very much!
Just insert those UL tags at the half of the iterations:
$arrayMovies = array( 'Forest Gump', 'The Hours', 'Mullholand Drive', 'Titanic', 'The Intouchables' );
$arrayMoviesCount = count( $arrayMovies );
echo '<ul>';
for( $i = 0; $i < $arrayMoviesCount; $i++ )
{
if( ceil( $arrayMoviesCount / 2 ) == $i )
{
echo '</ul><ul>';
}
echo sprintf( '<li>%s</li>', $arrayMovies[$i] );
}
echo '</ul>';
Output of the above code:
<ul>
<li>Forest Gump</li>
<li>The Hours</li>
<li>Mullholand Drive</li>
</ul>
<ul>
<li>Titanic</li>
<li>The Intouchables</li>
</ul>
The ceil is required for lists with an odd number of entries; using ceil will result in the first list having one entry more. If the additional (not-even) entry should be displayed in the second list, you could replace ceil by floor.
Sorry for the previous answer, I didn't understand what you wanted to exactly do.
If the problem is: "I want to categorize movies", then use an associative array instead.
Else, if you just want to display two movies in two coloumns, I would suggest you this:
$i = 1;
$flagCounter = 0;
echo "<ul>";
foreach($arrayMovies as $k=>$v)
{
if ($flagCounter != 2) {
echo "<li><input type=\"checkbox\" id=\"flat-$i\" name=\"$genre-$i\" value=\"$k\">
<label for=\"flat-$i\">$v</label></li>";
$i++;
$flagCounter++;
}
else {
echo "</ul><ul>";
echo "<li><input type=\"checkbox\" id=\"flat-$i\" name=\"$genre-$i\" value=\"$k\">
<label for=\"flat-$i\">$v</label></li>";
$i++;
$flagCounter = 1;
}
}
echo "</ul>";
To be honest at all, I don't really trust this solution, this is just a workaround for your case. If you're interested in a better one, try using an associative array with a structure like such:
$yourArray = array ( "Category" => array ("movie1","movie2") [and so on...] );
In this way, you will be able to display everything more clearly, being able to access to both movies and categories!
Also, why did you choose to use a list instead of a table for displaying these?
And.. Where does the variable $genre come from? Is this all your code or what? If not, can you please provide us the structure of your array?
I am new to php and I am trying to create a simple bit of code that prints a "last" class at the start of the last element in a "while" loop. There are only two items in the loop (blog excerpts) hence why I have tried below with the if ($i == 1)... Thanks for any help.
Here is my code so far - which only returns the p
<?php
$i = 0;
if($i == 1) {
echo '<p class="last">';
}
else {
echo '<p>';
}
?>
EDIT:
Thanks for the help so far. Greatly appreciated - I have provided a bit more information below (I posted late at night, so I realise I haven't been all that clear).
This is the full piece of code I am trying to write. It is pulling blog excerpts from Wordpress - currently limited to 2 blog articles.
<?php
$posts = new WP_Query('showposts=2');
while ( $posts->have_posts() ) : $posts->the_post();
?>
<p><?php echo the_title(); ?><br/>
<?php echo substr(get_the_excerpt(), 0,200); ?>... Read More</p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
I am wanting to add the class "last" to the p at the start of line 5 - for the last blog except only.
Thanks again.
Nick's answer says almost all that needs to be said.
The only thing I might add is a slight variation to save duplication particularly if the the contents of your paragraph tags is more complicated.
This might be better done with the following tweak on Nick's code:
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<?php
$numLoops = 2;
$ctext=""
for($i=0; $i<$numLoops; $i++) {
$info="whatever";
if($i == (numLoops-1)) {
$ctext=' class="last"';
}
echo "<p${ctext}>${info}</p>\n";
}
?>
</div>
</body>
Cheers
So you have two paragraphs, and you want to apply the class "last" to the last one? Sounds like this is better handled with CSS
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<p> first info</p>
<p> last info </p>
</div>
</body>
OR if you want to learn about loops
<?php
$numLoops = 2;
for($i=0; $i<$numLoops; $i++) {
if($i == (numLoops-1)) {
echo '<p class="last">';
} else {
echo '<p>';
}
}
What we are doing here with the for loop is initially setting the variable $i=0; then setting a test that says keep looping as long as the variable is less than the number of loops we want do do. Next we are setting what to do each loop, in this case we increment our variable by one each time.
First loop
i=0, we see that 0 is < 2 so we continue
Second loop
We execute the $i++ so we increment $i by 1 from 0 to $i=1,
we test and see $i=1 is still less than 2 so we continue.
Third attempted loop
We increment $i by 1 and get $i=2.
We test to see if this is less than 2, but it is NOT so we do not execute code in the loop
The main issue is that you don't have a loop in your code, and if you did you aren't incrementing your variable $i
I have a simple working PHP script to write an HTML table from a text file that contains a single column of data that contains HTML links. This writes the data horizontally in a row across 5 or 6 columns as I want it to. But I am looking to set up a script with a loop that will take this list of data and input it into the table until it finishes the data list, so that I do not have to hard code each table cell individually. Just let the script create each table cell, at 5 or 6 columns across (whichever I need for this specific table), go to the next row, etc., until it runs out of data. The data in the data file will be added to on a regular basis, so the table will not be of a certain fixed length forever. I am using the echo command so that I can add some more HTML formatting later on.
Even though my existing script is simple and it works, if you can think of a better way of doing what I am trying to do, all suggestions are appreciated.
Thanks in advance, Stan...
PHP code follows:
<?php
$item = #fopen('linklist.txt', "r");
if ($item) { while (!feof($item)) { $lines[] = fgets($item, 4096); } fclose($item); }
echo'
<TABLE border="1">
<TR>
<TD>'.($lines[1]).'</td>
<TD>'.($lines[2]).'</td>
<TD>'.($lines[3]).'</td>
<TD>'.($lines[4]).'</td>
<TD>'.($lines[5]).'</td>
<TD>'.($lines[6]).'</td>
</tr>
<TR>
<TD>'.($lines[7]).'</td>
<TD>'.($lines[8]).'</td>
<TD>'.($lines[9]).'</td>
<TD>'.($lines[10]).'</td>
<TD>'.($lines[11]).'</td>
<TD>'.($lines[12]).'</td>
</tr>
<!-- And So On, And So On, ETC -->
</table>'
?>
<?php
echo '<table border="1"><tr>';
for($i=0; $i<sizeof($lines); $i++) {
echo '<td>'.$lines[$i].'</td>';
if(($i+1)%6==0 && $i!=sizeof($lines)-1) echo '</tr><tr>';
}
echo '</tr></table>';
?>
Explanation:
Repeats through each "line" and writes the <td>value</td>
If a line is a multiple of 6, after writing the value, then close the row, and open another (unless it's the last one, since it will close the row after the loop as well.
(I assume you meant to start on $line[0], but if you really meant to start on $line[1], just change the $i=0; to $i=1;, remove the +1 in the row check, and change $i<sizeof to $i<=sizeof
$lines = chunk_split($lines,6);
?>
<TABLE border="1">
<? foreach ($lines as $row): ?>
<TR>
<? foreach ($row as $value): ?>
<TD><?=$value?></td>
<? endforeach ?>
<TR>
<? endforeach ?>
</TABLE>
In pseudo code...
x = 0
echo '<TABLE border="1">'
For each $line in $lines {
x = x + 1
if x = 1 {
echo '<TR>'
}
echo <TD>'.($line).'</TD>
if x = 6 {
echo '</TR>'
x = 0
}
}
echo '</TABLE>'
Note the use of the $line object to hold the value of the $line array element.
hth
If you use a loop, you can also avoid reading the complete file into memory, which might be beneficial:
<?php
$item = #fopen('linklist.txt', "r");
if ($item) {
echo'<TABLE border="1">';
$i=0;
$lines=array();
while (!feof($item)) {
$line[] = fgets($item, 4096);
$i++;
if ($i==6) {
echo "<tr>";
echo '<TD>'.($lines[0]).'</td>';
echo '<TD>'.($lines[1]).'</td>';
echo '<TD>'.($lines[2]).'</td>';
echo '<TD>'.($lines[3]).'</td>';
echo '<TD>'.($lines[4]).'</td>';
echo '<TD>'.($lines[5]).'</td>';
echo "<tr>";
$i=0;
$lines=array();
}
}
echo '</table>';
fclose($item);
}
?>
So what I'm trying to do is select all the distinct months from my database and then print them in a list. That, I can accomplish. The problem lies in the fact that I need my list to be two column. The way that I achieve this with CSS is by using 2 different div's "left" and "right" which are floated next to each other. This poses a problem with PHP because it needs to echo a div close and a new div open after it echoes the sixth month. Then it needs to start again from where it left off and finish. I can't just list all of the months in the HTML, either because I don't want it to list a month if I don't have any records in the DB for that month, yet. Any ideas? I hope I was clear enough!
Thanks!
-williamg
Something like this should work (the basic idea being to just keep a count of the months an increment it as you loop through them):
<div class="left">
<?php
$x = 1;
foreach($months as $month) {
# switch to the right div on the 7th month
if ($x == 7) {
echo '</div><div class="right">';
}
echo "<div class=\"row\">{$month}</div>";
# increment x for each row
$x++;
}
</div>
<?php
$numberOfMonths = count($months);
$halfwayPoint = ceil($numberOfMonths / 2);
echo "<div class=\"left\">";
for($i=0; $i<$halfwayPoint; $i++){
echo $months[$i] . "<br />";
}
echo "</div><div class=\"right\">";
for($i=$halfwayPoint; $i<$numberOfMonths; $i++){
echo $months[$i] . "<br />";
}
echo "</div>";
?>
Rant: on
When displaying tabular data, use table instead of floating div. It will make sense when viewing the page with css disabled. If you use floated div, then you data will displayed all way down. Not all table usage is bad. People often hate table so much, so using floated div. Table only bad when used for page layout.
Rant: off
When I need to have certain content displayed with some open, close, and in-between extra character, I will make use of implode. This is the example:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
You can extends this to almost anything. Array and implode is the power that php have for many years. You will never needed any if to check if it last element, then insert the closing character, or check if it first element, then insert opening character, or print the additional character between elements.
Hope this help.
Update:
My bad for misread the main problems asked. Sorry for the rant ;)
Here is my code to make a data displayed in 2 column:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
Other solution is using CSS to format the output, so you just put the div top to down, then the css make the parent container only fit the 6 item vertically, and put the rest to the right of existing content. I don't know much about it, since it usually provided by fellow css designer or my client.
Example assumes you have an array of objects.
<div style="width:150px; float:left;">
<ul>
<?php
$c = count($categories);
$s = ($c / 3); // change 3 to the number of columns you want to have.
$i=1;
foreach($categories as $category)
{
echo '<li>' . $category->CategoryLabel . '</a></li>';
if($i != 0 && $i % $s == 0)
{
?>
</ul>
</div>
<div style="width:150px; float:left;">
<ul>
<?php
}
$i++;
}
?>
</ul>
</div>