convert the result set foreach to for loop in php - 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..

Related

PHP Foreach in Foreach with if statement

I am writing a web and i got stuck. PHP is not my language of choice, so I'm not that used to it. But lets look at the problem:
$i = 1;
$n = 0;
<div class="hs_client_logo_slider">
<?php
foreach ($hashone_client_logo_image as $hashone_client_logo_image_single) {
foreach ($hashone_logo_list as $hashone_logo_url) {
if ($i > $n) {
?>
<a target="_blank" href="<?php echo esc_url($hashone_logo_url) ?>">
<img alt="<?php _e('logo','hashone') ?>" src="<?php echo esc_url(wp_get_attachment_url($hashone_client_logo_image_single)); ?>">
</a>
<?php
$n = $n + 1;
continue 2;
} else {
$i = $i + 1;
continue 1;
Basically I am trying to do:
Foreach (x as y) && Foreach (a as b) {
/* Magic happens here */
In the first foreach I have images and in the second one links. And for the first image I need the first link stored in logo_list, for the second image I need second link and so on... So I tried If statement that could take care of it, but for some reason it doesn't work.
Now it gives me first image with first link, but every image after that is stuck with second link. Do you have any idea what to do?
I'm glad for everyone who tries to help me out. Thank you very much.
Try a different approach. First of all, prepare your data before passing it to foreach loop that is responsible for generating view, then your foreach loop will be much easier to read and maintain.
If every 1st element should go with 1st element in the second foreach, 2nd to 2nd, 3rd to 3rd and so on, then using two foreach loops is redundant. Use only 1 foreach and in every foreach iteration take its index (it can be a separate incremented variable) and take element from second array by index. You can also use a standard for loop and it should be even simpler to implement.

How to create simple pagination in PHP page

Below is my Code.
<?php
$folder_name=$_GET['folder_name'];
$dirname = "customized_kits/images/";
$images = glob($dirname."*");
$filecount = count( $images );
$i=0;
for($i=0;$i<200;$i++) { ?>
<div class="col-md-2"> <div class="photos">
<div id="images1">
<a href=# data-lightbox="roadtrip">
<?php
if($filecount>$i) {
$filename = substr($images[$i], strrpos($images[$i], '/') + 1);
echo '<img src="'.$images[$i].'" style="width:150px;height:150px" /><br/>';
?>
<i class="fa fa-remove"></i>
<?php } else {
echo '<a ><img style="width:150px;height:150px;background-color:#eee" /></a>';
} ?>
</div>
</div>
</div>
<?php } ?>
Here I created 200 boxes with foreach loop I want to show 20 divs for single page and with help of pagination I want to show other divs.I searched in many websites I didnt get exact answer please help me to get out of this issue.
Okay so from your code you can have 200 values of $i and you want to paginate them in segments of 20. Let us start off by adding a script above your code to get the range that needs to be displayed. Page number comes as a GET parameter in number. ex example.com/feeds?number=2.
<?php
$pageno = $_GET['number']; // Page number from frontend
// Now this value will give you 1,2,3 etc
$start = $pageno*20;
// $start contains the initial offset or the value of `$i` from to start
for($i=$start;$i<$start+20;$i++) {
// Will only show 20 elements on the page
}
?>
Remember this is a very basic example. Although i would recommend using range in sql query instead so you don't have to load the complete dataset in each query.
More explanation
Suppose you have M results and you want to show N results on each page, the results on page x would start from x*N to x*(N+1) pure math here. In your code you are iterating $i over the whole loop rather just iterate over that specific range to get results. The value of x is the example is the page number that we get from number in GET verb.

if last element echo'class="last"'

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

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.

problem in showing 3 images in a row

hey guys , i know this is a stupid question but i hanged in solving it
i wrote a block of php code to show images from mysql
echo "<table><tr> ";
while($cat = $db->sql_fetchrow($catinfo)) {
echo '
<td>
<ul id="three-col" class="press">
<li>
<div class="post-content">
<a class="zoom1" href="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'">
<img src="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'" alt="artistry (via powerbooktrance)" />
</a>
</div>';
for ($i=0; $i>2; $i++) {
echo "</tr><tr>";
}
}
echo "</li></ul></td></tr></table>";
but with this code everything goes wrong and it doesnt break after each 3 images in row
i even used
if ($i>2) {
echo "</td></tr><tr>";
}
but as u know it only breaks the tr after image number 3 not every row
im really sorry for my foolish question
Try this:
echo "<table><tr> ";
$counter = 0;
while($cat = $db->sql_fetchrow($catinfo)) {
$counter++;
echo '
<td>
<ul id="three-col" class="press">
<li>
<div class="post-content">
<a class="zoom1" href="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'">
<img src="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'" alt="artistry (via powerbooktrance)" />
</a>
</div>
';
if ( $counter == 3 ) {
echo '</tr><tr>';
$counter = 0;
}
}
echo "</li></ul></td></tr></table>";
First off, the
for ($i=0; $i>2; $i++) {
should probably be
for ($i=0; $i < 2; $i++) {
There may be additional logic issues (looking)...
Indeed the logic seems utterly flawed, for ex. there doesn't appear to be anything which detects the the third image etc...
==> I suggest you try the snippet from tambler's answer. No point in trying and fix this one... but if you must:
the for ($i=0; $i>2; $i++) { loop is unnecessary. Even when fixed to $i < 2 (or 3...) this doesn't do anything useful.
with each new image you output a <td>, this needs to be closed with a </td>
there need to be a counter (the $i) you hint at in your snippet isn't valid
the counter is to be systematically incremented with each image
a test is to be added towards the end of the loop:
If counter >= 3 (or 2, if you make it 0-based)
reset counter;
emit ""
Also the <ul> and <li> and their respective closing tags are misplaced.
Where's you're </td> tag?
All your TDs have to be inside the TRs. You have to close the UL and TD before your TR.

Categories