ForEach loop: Output something different on every second result - php

I have two for each loops and I am trying to output something different for each second result:
foreach ($wppost as $wp) {
$wp_title = $wp->post_title;
$wp_date = strtotime($wp->post_date);
$wp_slug = $wp->post_name;
$wp_id = $wp->ID;
// Start Permalink Template
$wp_showurl = $wp_url;
$wp_showurl = str_replace("%year%", date('Y', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%monthnum%", date('m', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%day%", date('d', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%hour%", date('H', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%minute%", date('i', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%second%", date('s', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%postname%", $wp_slug, $wp_showurl);
$wp_showurl = str_replace("%post_id%", $wp_id, $wp_showurl);
// Stop Permalink Template
$wp_posturl = $blog_address . $wp_showurl;
echo '<li>'.$wp_title.'</li>';
}
For this one I want it to echo <li class="even"> instead of just <li> for each second result. I think this will have to be changed to a for loop to accomplished this but I am not sure how that is done without breaking it.
Exact same for this one:
if(is_array($commenters)) {
foreach ($commenters as $k) {
?><li><?php
if($ns_options["make_links"] == 1) {
$url = ns_get_user_url($k->poster_id);
if(trim($url) != '')
{
echo "<a href='" . $url . "'>";
}
}
if($ns_options["make_links"] == 2) {
$url = ns_get_user_profile($k->poster_id);
echo "<a href='" . $url . "'>";
}
$name = $bbdb->get_var("
SELECT user_login
FROM $bbdb->users
WHERE ID = $k->poster_id");
echo ns_substr_ellipse($name, $ns_options["name_limit"]);
if(trim($url) != '' && $ns_options["make_links"] == 1) {
echo "</a>";
}
if($ns_options["make_links"] == 2) {
echo "</a>";
}
if ($ns_options["show_posts"] == 1)
{
echo " (" . $k->num_posts . ")\n";
}
echo $ns_options["end_html"] . "\n";
unset($url);
}
} else {
?></li><?php
}
Thanks,
Wade

You can create a "counting" variable, and then use the result of $count % 2 to determine if it is an odd or even row:
$rowCount = 0;
foreach ($wppost as $wp) {
// stripping stuff:
echo '<li';
// increase $rowCount - if the remainder of a division by 2 is 1, echo extra class info:
if ($rowCount++ % 2 == 1 ) echo ' class="even"';
echo '>'.$wp_title.'</li>';
}
if(is_array($commenters)) {
$commentCount = 0;
foreach ($commenters as $k) {
?><li<?php echo ($commentCount++%2==1)?' class="even"':''?>><?php
//stripped the rest of the loop:
}
}

I have done something like this, maybe this will help someone who is searching for this type of solutions.
#foreach ($occasions as $key => $occasion)
#if ($key++ % 2 == 1)
<li style="background: #f6f6f6;">
#else
<li>
#endif
{{$occasion->name}}</li>
#endforeach

Related

Cache API Calls

I have following code to call and echo some API calls from a site.
function popular_uploads() {
// If no saved data exists in the cache
if ($json_data === false) {
// Fetch new data from remote URL
$gameid = $instance['code1'];
$url = ("http://thegamesdb.net/api/GetGame.php?id=".$gameid."");
$json = file_get_contents($url);
$json_data = json_decode($json, false);
set_transient('my_unique_identifier', $json_data, 3600); $json_data = get_transient('my_unique_identifier');
}
foreach ( $json_data->items as $item ) {
$title=$item->Game->GameTitle;
$boxartw=$item->Game->Images->boxart[0];
$boxart=$item->Game->Images->boxart[1];
if ($boxart == NULL) {
$boxart = $boxartw;}
$publisher=$item->Game->Publisher;
$releasedate=$item->Game->ReleaseDate;
$newdate = date("d/m/Y", strtotime($releasedate));
$newday = date("d", strtotime($releasedate));
$newmon = date("m", strtotime($releasedate));
$newyear = date("Y", strtotime($releasedate));
echo '<div class="upcoming_games_side">';
echo '<div class="upcomig_bg"style="background-image:url(http://thegamesdb.net/banners/_gameviewcache/' .$boxart. ');></div>';
echo '<div class="dark-screen-uc"></div>';
echo '<img class="game-boxart_uc" alt="" src="http://thegamesdb.net/banners/_gameviewcache/'.$boxart.'"/>';
if ($title == null){
echo "N/A"; }else{
echo '<h1 class="title_uc">'.$title.'</h1>';}
if ($publisher == null){
echo "N/A"; }else{
echo '<p class="pub_uc">'.$publisher.'</p>';
}
if ($newdate == "01-01-1970"){
echo "N/A";
}else{
echo '<date class="date_uc">'.$newdate.'</date>';
}
$target = mktime(0, 0, 0, $newday, $newmon, $newyear) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
if ($days == "0"){
echo "N/A"; }else{
echo '<date class="count_uc">'.$days.'</date>';}
echo '</div>';
}
}
But it's not working and doesn't Cache API data. So Where is my mistake and wahts part's of my code's are Wrong? I'd appreciate any help.
By the way, it's a Wordpress plugin.

How to add a count == 0 to this?

I would like to add a count == 0 which if it is the case, just outputs 'please contact us to find out the dates', but I can't seem to get it to work. Please can someone advise?
$count = 0;
$your_repeater = get_field('add_date');
if ($your_repeater) {
while (have_rows('add_date')):
the_row();
$count++;
$my_field = get_sub_field('course_date');
if ($count == 0) {
echo 'please contact us to find out dates';
} else {
echo '';
}
if ($count == 1) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
// echo $my_field .', ';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>1. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo 'Contact us to find out more';
} else {
echo '';
}
}
if ($count == 2) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>2. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo '<img src="' .bloginfo('url').'/wp-content/themes/derbyskillbuild site/images/hourglass.png" />';
} else {
echo '';
}
}
if ($count == 3) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b> 3. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
} else {
echo '';
}
}
if ($count == 4) {
}
if ($count == 5) {
}
echo '</ul>';
endwhile;
}
It appears that you are checking the count way too soon in your code.
You start with a $count = 0;, but then in the while loop you first do $count++. So, at this point, the count is 1. Then a few lines later you check this:
if ($count == 0) {
echo 'please contact us to find out dates';
}
This will never return true, since you just did a $count++ from 0, so at this point it's always at least 1. It seems that this check should be outside of your while loop and you're currently closing the loop way too late.

PHP If first result in grouped MySQL array

I'm selecting a recordset from MySQL which is grouped by release_date using $group_date.
What I need to do is calculate whether it is the first iteration of $group_date and output different HTML compared to if it isn't the first iteration of $group_date.
The different HTML is as simple as not outputting the first echo '</div>'; in the code below.
I've tried variations of $i=1 and $i++ but I can't seem to get it working as all the code examples i've found are based on normal results, not when they've been grouped.
<?php
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
if ($group_date !== substr($row["release_date"], 0, 10)) {
$group_date = substr($row["release_date"], 0, 10);
echo '</div>';
echo $title == "" ? "" : $title;
$title = "";
echo '<div class="divide-bottom">';
echo '<h3>' . $group_date . '</h3>';
?>
try that
if ($group_date != substr($row["release_date"], 0, 10)) {
$iteration = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$release_date = substr($row["release_date"], 0, 10);
if ($group_date == $releaseDate && $iteration == 0) {
echo '<h3>' . $group_date . '</h3>';
$iteration++;
}
echo '<div>' . $title . '</div>';
echo '<div class="divide-bottom">';
}
Update - this seems to work fine for me:
<?php
$iteration = 0;
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
if ($group_date !== substr($row["release_date"], 0, 10)) {
$group_date = substr($row["release_date"], 0, 10);
if ($iteration == 0) {
echo $title == "" ? "" : $title;
$title = "";
echo '<div class="divide-bottom">';
echo '<h3>' . $group_date . '</h3>';
$iteration++;
}
else {
echo '</div>';
echo $title == "" ? "" : $title;
$title = "";
echo '<div class="divide-bottom">';
echo '<h3>' . $group_date . '</h3>';
}
?>

add an if echo statement to my search engine

I have a search engine and because of the paralympics, I want people to be able to see a h1 countdown I have placed at the top of my site. Underneath will be the looped results from my database. Any ideas where I go wrong? because in this if, it won't echo the h1 tag at all. I would like to above my results.
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0) {
$query .= " OR ";
}
$query .= "keywords LIKE '%{$each}%'";
}
// Don't append the ORDER BY until after the loop
$query .= "ORDER BY rank";
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error($connect));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p maxlength="10" class="kk">' . $description . '</p>' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords"></p>' . PHP_EOL;
}
} else {
echo "No results found for \"<b>{$k}</b>\"";
}
if ($k = "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
if ($k = "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
Will always print the <h1>. You're doing assignment rather than comparison. Try:
if ($k == "Paralympics 2012")
Also, verify that $k is what you expect it to be when debugging.
One equals (=) assigns, and two/three (==/===) compares. The line
if ($k = "Paralympics 2012") {
Assigns $k to a string, which always returns true, because any string other than an empty one ("") is truthy. Try this:
if ($k === "Paralympics 2012") {
First things first, the <h1> is always displaying, opposite of what you're question states. It's always displaying due to the fact that you're doing an assignment of a non-false value with:
if ($k = "Paralympics 2012") {
Update that to use a comparison to fix that logic issue.
if ($k == "Paralympics 2012") {
Next, to get it to display above your results, you need to actually move that if-statement above the loop that echos the results. Try placing it in the if ($numrows > 0) { block, like this:
if ($numrows > 0) {
if ($k == "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
while ($row = mysql_fetch_assoc($query)) {
...

Show first letter of a list once?

I have a list of directory name and need to get the first letter from each name and just display it once before the start of that lettered group ie;
what I have:
1
2
3
4
5
Aberdeen
Arundel
Aberyswith
Bath
Bristol
Brighton
Cardiff
coventry
what I would like:
#
1
2
3
4
5
A
Aberdeen
Arundel
Aberyswith
B
Bath
Bristol
Brighton
C
Cardiff
coventry
function htmlDirList($subdirs) {
global $z_self, $z_img_play, $z_img_lofi, $z_img_more, $z_admin,
$z_img_down, $z_img_new, $zc;
$now = time();
$diff = $zc['new_time']*60*60*24;
$num = 0;
$dir_list_len = $zc['dir_list_len'];
if ($zc['low']) { $dir_list_len -= 2; }
$html = "";
$checkbox = ($z_admin || ($zc['playlists'] && $zc['session_pls']));
/**/
$row = 0;
$items = sizeof($subdirs);
$cat_cols = "2";
$rows_in_col = ceil($items/$cat_cols);
if ($rows_in_col < $cat_cols) { $cat_cols = ceil($items/$rows_in_col); }
$col_width = round(100 / $cat_cols);
$html = "<table width='600'><tr>";
$i = 0;
/**/
foreach ($subdirs as $subdir => $opts) {
if ($row == 0) {
$class = ($cat_cols != ++$i) ? ' class="z_artistcols"' : '';
$html .= "<td $class valign='top' nowrap='nowrap' width='$col_width%'>";
}
/*$currentleter = substr($opts, 0 , 1);
if($lastletter != $currentleter){
echo $currentleter;
$lastletter = $currentleter;
}*/
if($alphabet != substr($opts,0,1)) {
echo strtoupper(substr($opts,0,1)); // add your html formatting too.
$alphabet = substr($opts,0,1);
}
$dir_len = $dir_list_len;
$dir = false;
$image = $opts['image'];
$new_beg = $new_end = "";
if (substr($subdir, -1) == "/") {
$dir = true;
$subdir = substr($subdir, 0, -1);
}
$path_raw = getURLencodedPath($subdir);
$href = "<a href='$path_raw";
if (!$dir) {
if ($zc['download'] && $zc['cmp_sel']) { $html .= "$href/.lp&l=8&m=9&c=0'>$z_img_down</a> "; }
if ($zc['play']) { $html .= "$href&l=8&m=0'>$z_img_play</a> "; }
if ($zc['low'] && ($zc['resample'] || $opts['lofi'])) { $html .= "$href&l=8&m=0&lf=true'>$z_img_lofi</a> "; }
if ($checkbox) { $html .= "<input type='checkbox' name='mp3s[]' value='$path_raw/.lp'/> "; }
$num++;
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
$dir_len -= 5;
if ($z_img_new) {
$new_end = $z_img_new;
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
}
}
$title = formatTitle(basename($subdir));
if (strlen($title) > $dir_len) {
$ht = " title=\"$title.\"";
$title = substr($title,0,$dir_len).$opts['mtime']."...";
} else {
$ht = "";
}
if ($zc['dir_list_year']) {
$di = getDirInfo($subdir);
if (!empty($di['year'])) $title .= " (".$di['year'].")";
}
$html .= "$href'$ht>$new_beg$title$new_end</a><br />";
$row = ++$row % $rows_in_col;
if ($row == 0) { $html .= "</td>"; }
}
if ($row != 0) $html .= "</td>";
$html .= "</tr></table>";
$arr['num'] = $num;
$arr['list'] = $html;
return $arr;
}
I need help to get work.
The following will display the list of directories, beginning each group with a first letter as beginning of the group (see codepad for proof):
(this assumes $dirs is array containing the names)
$cur_let = null;
foreach ($dirs as $dir) {
if ($cur_let !== strtoupper(substr($dir,0,1))){
$cur_let = strtoupper(substr($dir,0,1));
echo $cur_let."\n";
}
echo $dir . "\n";
}
You just need to add some formatting on your own, suited to your needs.
Edit:
Version grouping under # sign entries that begin with a number, can look like that:
$cur_let = null;
foreach ($dirs as $dir) {
$first_let = (is_numeric(strtoupper(substr($dir,0,1))) ? '#' : strtoupper(substr($dir,0,1)));
if ($cur_let !== $first_let){
$cur_let = $first_let;
echo $cur_let."\n";
}
echo $dir . "\n";
}
Please see codepad as a proof.
Is this what you are looking for?
<?php
$places = array(
'Aberdeen',
'Arundel',
'Aberyswith',
'Bath',
'Bristol',
'Brighton',
'Cardiff',
'coventry'
);
$first_letter = $places[0][0];
foreach($places as $p)
{
if(strtolower($p[0])!=$first_letter)
{
echo "<b>" . strtoupper($p[0]) . "</b><br/>";
$first_letter = strtolower($p[0]);
}
echo $p . "<br/>";
}
?>
Prints:
A
Aberdeen
Arundel
Aberyswith
B
Bath
Bristol
Brighton
C
Cardiff
coventry
My approach would be to generate a second array that associates the first letter to the array of names that begin with that letter.
$dirs; // assumed this contains your array of names
$groupedDirs = array();
foreach ($dirs as $dir) {
$firstLetter = strtoupper($dir[0]);
$groupedDirs[$firstLetter][] = $dir;
}
Then, you can iterate on $groupedDirs to print out the list.
<?php foreach ($groupedDirs as $group => $dirs): ?>
<?php echo $group; ?>
<?php foreach ($dirs as $dir): ?>
<?php echo $dir; ?>
<?php endforeach; ?>
<?php endforeach; ?>
This allows for a clean separation between two separate tasks: figuring out what the groups are and, secondly, displaying the grouped list. By keeping these tasks separate, not only is the code for each one clearer, but you can reuse either part for different circumstances.
Use something like this, change it to output the HTML the way you want thouugh:
sort($subdirs);
$count = count($subdirs);
$lastLetter = '';
foreach($subdirs as $subdir => $opts){
if(substr($subdir,0,1) !== $lastLetter){
$lastLetter = substr($subdir,0,1);
echo '<br /><div style="font-weight: bold;">'.strtoupper($lastLetter).'</div>';
}
echo '<div>'.$subdir.'</div>';
}
EDIT
Just realized $subdir is associative, made the change above:

Categories