PHP Foreach in Foreach with if statement - php

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.

Related

Pass links as variable in php and echo it on html

i must pass multiple link as variables on php
ex: www.mysite.com/dl.php?link=www.google.com&link2=yahoo.com&link3=youtube.com and so on, there is a variable number of links, and then i want to put them on and html page generated dynamically based on the number of links i inputed, in the example i did, the links was 3, so it must be:
<html><center>
Click to download part 1
Click to download part 2
Click to download part 3
</center></html>
can someone help me with this problem?
Parameters you append on your URL can be accessed through $_GET in php.
Take a look at this page: http://php.net/manual/en/reserved.variables.get.php
Update: If you have a variable number of get parameters and you want to get them all just use a foreach loop:
foreach($_GET as $key => $url) {
echo $url;
}
Instead of using different parameter names for all urls, use an array:
www.mysite.com/dl.php?link[]=www.google.com&link[]=yahoo.com&link[]=youtube.com
Then, in dl.php, $_GET['link'] is an array. You can iterate like this:
for ($i = 0; $i < count($_GET['link']); ++$i) {
echo 'Click to download part ' . ($i + 1) . '';
}
If URL = www.mysite.com/dl.php?link1=www.google.com&link2=yahoo.com&link3=youtube.com
<?php
for($i = 0; $i < count($_GET); $i++)
{
?>
Click to download part <?php echo ($i+1);?>
<?php
}
?>
If the only get value that is the URLs then just loop through...
foreach ($_GET as $url)
{
echo $url
}

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

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..

Divide mysql query to fit divs

Sorry if the title is a bit confusing, I tried my best!
So basically I have 4 column divs that each contains 5 links for example. The links come from a table in my database, so new links are added and some others deleted, hence why I need to do it via database instead of writing it by hand. Now my issue is to divide the array in order to show 5 links per column (so when 5 links have been placed, div is closed and a new one is opened, unless there is no more link.
for example:
<div class="column">
Link
Link
Link
Link
Link
</div>
<div class="column">
Link
Link
Link
Link
Link
</div>
etc.
Thanks to anyone!
The PHP function array_chunk is nice to distribute an array of links into columns:
$columns = array_chunk($rows, 5);
foreach ($columns as $links)
{
echo '<div class="column">', "\n";
foreach ($links as $link)
printf("Link", $link);
echo '</div>', "\n";
}
I don't know your column names nor how you query the database, so I don't have any array indexes here written out. But I think you'll get the idea.
How about using the modulo operator
<div class="column">
for ($i = 0; $i < $nRow; $i++) {
if ($i % 5 == 0 && $i) {
echo '</div><div class="column">';
}
echo "<a href='{$links[$i]}'>Link</a>";
}
</div>

Multi column dynamic PHP list

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>

Categories