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>';
}
?>
Related
I have a foreach statement in my app that echos a list of my database results:
<?php
foreach($featured_projects as $fp) {
echo '<div class="result">';
echo $fp['project_name'];
echo '</div>';
}
?>
I would like to:
On every third result, give the div a different class. How can I achieve this?
You can use a counter and the modulo/modulus operator as per below:
<?php
// control variable
$counter = 0;
foreach($featured_projects as $fp) {
// reset the variable
$class = '';
// on every third result, set the variable value
if(++$counter % 3 === 0) {
$class = ' third';
}
// your code with the variable that holds the desirable CSS class name
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
foreach ($featured_projects as $i => $fp) {
echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
If the $featured_projects array is based on incremental index you could simply use the index and the modulo % operator.
Otherwise you would have to add a counter.
http://php.net/manual/en/language.operators.arithmetic.php
add a counter in this loop and check if counter equals three and apply class.
Using a counter and modulo operator this is easy to implement
<?php
foreach($featured_projects as $fp) {
if(++$i % 3 === 0) {
$class = ' something';
} else {
$class = '';
}
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
$i = 0;
foreach($featured_projects as $fp) {
echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
echo $fp['project_name'];
echo '</div>';
}
?>
What leaves your code mostly in tact would be
<?php
$i = 1;
foreach($featured_projects as $fp) {
printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
echo $fp['project_name'];
echo '</div>';
$i++;
}
?>
But you may want to consider using a for or while construct around "each($featured_projects)" (see http://php.net/manual/en/function.each.php) which may result in neater code.
<?php
$counter = 0;
foreach ($featured_projects as $fp) {
echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
You can add a counter in loop ...try the following...
<?php
$i = 0;
foreach($featured_projects as $fp) {
$i = ++$i;
if(($i%3) == 0)
{
$class1 = 'test1';
}
else
{
$class1 = 'test2';
}
echo '<div class="'.$class1.'">';
echo $fp['project_name'];
echo '</div>';
}
?>
This is the working version, sorry for my prev version:
<?php
$featured_projects[0]['project_name'] = "pippo";
$featured_projects[1]['project_name'] = "pippo2";
$featured_projects[2]['project_name'] = "pippo3";
$class[0] = "class1";
$class[1] = "class2";
$i=0;
foreach($featured_projects as $fp) {
$i++;
if ($i == 3) {
$c = $class[1];
$i=0;
} else {
$c = $class[0];
}
echo "<div class=\"$c\">";
echo $fp['project_name'];
echo "</div>\n";
}
?>
Produces:
<div class="class1">pippo</div>
<div class="class1">pippo2</div>
<div class="class2">pippo3</div>
I have a repeater from ACF and what I want to is loop and count the items and based on the counted items output a particular css class.
Can I get help so the output of css classes depends on the counted items. For example if there was six items the class would be col-6 etc...
<?php
if( have_rows('rainbow') ):
$counter = 0;
while( have_rows('rainbow') ): the_row();
// vars
$name = get_sub_field('name');
$age = get_sub_field('age');
$cssClass = 'col';
for($i = 0; $i < $counter; $i++) {
if($counter === 6) {
$cssClass = 'col-lg-4';
} elseif ($counter == 4) {
$cssClass = 'col-xl-6';
}
else {
$cssClass = 'col';
}
}
echo '<div class=\'' . $cssClass. '\'>';
echo "<h4>" . $name . "</h4>";
echo "<p>" . $age . "</p>";
echo $counter;
echo '</div>';
$counter++;
endwhile;
endif;
?>
Don't know why are you using for loop here, $i < $counter this condition cant be true because $i and $counter both of them started from 0. so 0 < 0 == FALSE
You just need to remove for loop inside your while loop.
Or, if you are using for loop somewhere else in your code, then you can just move your conditions outside the for loop.
Second Solution:
Second, if you start $counter from 1 then you can achieve your desired result as given example:
<?php
$array = array(1,2,3,4,5,6);
$counter = 1;
foreach ($array as $key => $value) {
$cssClass = 'col';
for($i = 0; $i < $counter; $i++) {
if($counter === 6) {
$cssClass = 'col-lg-4';
} elseif ($counter == 4) {
$cssClass = 'col-xl-6';
}
else {
$cssClass = 'col';
}
}
echo $cssClass."<br/>";
$counter++;
}
?>
Result:
col
col
col
col-xl-6
col
col-lg-4
<?php
$counter = 1;
while( have_rows('rainbow') ): the_row();
// vars
$name = get_sub_field('name');
$age = get_sub_field('age');
if ( $counter == 4 ) {
$cssClass = 'col-xl-6';
} elseif ( $counter == 6 ) {
$cssClass = 'col-lg-4';
} else {
$cssClass = 'col';
}
echo '<div class="' . $cssClass . '">';
echo "<h4>" . $name . "</h4>";
echo "<p>" . $age . "</p>";
echo $counter;
echo '</div>';
$counter++;
endwhile;
try this
if (isset($_GET['q'])){
$q = $_GET['q'];
//variables
$sql = "SELECT * FROM products WHERE product LIKE '%$q%' OR search LIKE '%$q%'";
$result = $conn->query($sql);
//check database
if($result->num_rows > 0){
while ($row = $result->fetch_array()){
$product = $row['product'];
$productImage = $row['product_image'];
$price = $row['price'];
$seller = $row['seller_name'];
$sellerImage = $row['seller_image'];
$desc = $row['description'];
$search = $row['search'];
$console = $row['console'];
$array = array($product, $price, $productImage);
$arrayDesc = array($desc, $sellerImage);
if (preg_match('/Game/', $seller)){
for ($num = 0; $num < 3; $num++) {
echo '<div class="tile col-md-4 col-sm-3">';
if($num == 0){
echo '<div class="tileTitleBox"><h4>' . $array[$num] . '</h4></div>';
}
if($num = 1){
echo '<p class="price">' . $array[$num] . '</p>';
}
if($num = 2){
echo '<img class="tilePic" src="' . $array[$num] . '"/>';
}
// if($num = 3){
// echo '<div class = "desc"><p>' . $array[$num] . '</p></div>';
// }
echo '</div>';
}//For Iteration Loop - TILE
for($count = 0; $count < 2; $count++){
echo '<div class="tile-description col-md-4 col-sm-3 hidden">';
if($count == 0){
echo '<div class="desc"><p>' . $arrayDesc[$count] . '</p></div>';
}
if($count == 1){
echo '<img class="sellerImg" src="' . $arrayDesc[$count] . '"/>';
}
echo '</div>';
}//end for loop - TILE-DESCRIPTION
So as you see above, I have one for loop which creates the "tile" and the second which is supposed to create the "tile-description". The first one works well to create a single div with the class of "tile" in which my remaining contents is loaded into the div. But in the second for loop the "desc" dev and the "sellerImg" div are separated. The loop needs to go through the array various times.
Shown Bellow:
You can see that the "Tile" div contains "tileTitleBox", "price", and "tilePic". But the "tile-description" which is hidden, is separated into two divs. As opposed to holding both elements inside the same div.
#sam-dufel rightly pointed out you're overwriting the iterator
if($num = 1){
But in fact you shouldn't use any loops here:
echo '<div class="tile col-md-4 col-sm-3">';
echo '<div class="tileTitleBox"><h4>' . $array[0] . '</h4></div>';
echo '<p class="price">' . $array[1] . '</p>';
echo '<img class="tilePic" src="' . $array[2] . '"/>';
echo '</div>';
echo '<div class="tile-description col-md-4 col-sm-3 hidden">';
echo '<div class="desc"><p>' . $arrayDesc[0] . '</p></div>';
echo '<img class="sellerImg" src="' . $arrayDesc[1] . '"/>';
echo '</div>';
I have a list of thousands of results and I want to group them alphanumerically for example, I need it to be like this:
<h1>0-9</h1>
<ul>
<li>011example</li>
<li>233example</li>
<li>65example</li>
</ul>
<h1>A</h1>
<ul>
<li>albert</li>
<li>alfred</li>
<li>annie</li>
</ul>
<h1>B</h1>
<ul>
<li>ben</li>
<li>bertie</li>
<li>burt</li>
</ul>
But I can't work out how to split or group my results into 0-9 and A-Z.
Currently I have:
<?php
$get_az = mysql_query("SELECT custom_22 FROM db_table1");
echo '<ul>';
while ($row = mysql_fetch_assoc($get_az)) {
$getfirstletter = substr($row['custom_22'], 0,1);
$name = $row['custom_22'];
echo '<h1>'.$getfirstletter.'</h1>';
echo '<li>'.$name.'</li>';
}
echo '</ul>';
?>
Order by the name and handle each letter one by one.
$get_az = mysql_query("SELECT custom_22 FROM db_table1 ORDER BY custom_22 ASC");
$current_first_letter = null;
while ($row = mysql_fetch_assoc($get_az)) {
$first_letter = strtolower(substr($row['custom_22'], 0, 1));
if (preg_match("/[0-9]/", $first_letter)) { // detect digits
$first_letter = "0-9";
}
if ($first_letter !== $current_first_letter) {
if ($current_first_letter !== null) {
echo '</ul>';
}
echo '<h1>' . $first_letter . '</h1>';
echo '<ul>';
}
$current_first_letter = $first_letter;
echo '<li>' . htmlentities($row['custom_22']) . '</li>';
}
if ($current_first_letter !== null) {
echo '</ul>';
}
I would do it this readable way:
$get_az = mysql_query('SELECT custom_22 FROM db_table1 ORDER BY custom_22');
$groups = array();
split results to groups
while ($row = mysql_fetch_assoc($get_az)) {
$firstLetter = strtolower(substr($row['custom_22'], 0, 1));
check for digits
if (is_numeric($firstLetter)) {
$firstLetter = '0-9';
}
if (isset($groups[$firstLetter]) === false) {
$groups[$firstLetter] = array();
}
$groups[$firstLetter][] = $row['custom_22'];
}
simply iterate over groups and echoes it
foreach ($groups as $h1 => $items) {
echo sprintf('<h1>%s</h1>', strtoupper(htmlspecialchars($h1)));
echo '<ul>';
foreach ($items as $item) {
echo sprintf('<li>%s</li>', htmlspecialchars($item));
}
echo '</ul>';
}
I have a block of PHP code that looks like this:
$flag = false;
if (empty($links))
{
echo '<h1>You have no uploaded images</h1><br />';
}
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div>';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
echo '<br>';
echo '</div>';
$flag = true;
}
I want the <div> to include a different class based on if it is even or odd. If it is even, it gets X class, if it's odd it gets Y class.
How do I do this in my case? I'm totally clueless and I don't know how to start!
Initialise a variable $count=0; before the loop. Then place the following in the loop: ++$count%2?"odd":"even".
$count = 0;
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div class="' . (++$count%2 ? "odd" : "even") . '">';
[...]
$i++;
echo '<div class="'.($i%2 ? 'odd':'even').'>';
[...]
before the foreach, declare a boolean:
$div_flag = false;
in the foreach, where you echo the div add this:
"class=".( $div_flag ? "'odd'" : "'even'" )
at the end of the foreach (or anywhere in it, really) add this:
$div_flag = !$div_flag;
If you're working on a prototype site, you could always implement a pure CSS solution:
div:nth-child(even) { /* Apply even class rules here */ }
div:nth-child(odd) { /* Apply odd class rules here */ }
The reason I recommend that you only use this for prototype sites is because the compatibility for :nth-child does not support IE8 or below.
Try something like this
$count = 0;
foreach($links as link) {
$count++;
print ($count % 2 == 1) ? "odd" : "even";
}
If you are using a modern browser, you can use CSS with something like this in your style sheet.
div:nth-child(odd)
{
background:#ff0000;
}
div:nth-child(even)
{
background:#0000ff;
}
Add a variable for your loop.
$c = true;
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div'.(($c = !$c)?' class="odd"':'').">
//echo '<div>';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
echo '<br>';
echo '</div>';
$flag = true;
}
Without counters:
<?php $toggle_class = 'even';?>
<?php foreach ($links as $link):?>
<?php $toggle_class = ($toggle_class == 'odd' ? 'even' : 'odd');?>
<div class="<?php echo $toggle_class;?>">
Your div content...
</div>
<?php endforeach;?>
This is the easy tricks
function check_odd_even($data){
if($data % 2 == 0){
$data = "Even";
}
else{
$data = "Odd";
}
return $data;
}
if (check_odd_even($index) == 'Odd'){
//layout 1....
}else{
//layout 2....
}