Displaying each item in an array a number of times - php

Hi guys this seems to be a very basic question,
I have an array of categories, and would like to display each one 4 times.they are all floating left, so each category is displayed as a row of 4 boxes.
however there are some divs which are boxes with border that are displayed with each iteration. It seems to be working but i dont know if it's the correct way to do it, as all the
categories are not organised. I want a header of the specific category to appear first thing each time the loop jumps to the next item in array;
Any help is welcome. please see code below.
[CODE]
<section class="prodList">
<?php
$loop = 4;
$prodNum = 0;
$categories = array("All","Clothes","Gadgets","Games");
foreach($categories as $cat){
echo "<h2> new cat: ".$cat."</h2>";
while($prodNum < count($categories)*$loop){
echo "<div class='viewerWishlistProdContainer'>
<div class='prodImageContainer'>
</div>
</div>
";
echo " <p>
<button class='sortBtns' onClick='alert(\'See all V'\)'>See all V</button>
</p>";
$prodNum ++;
}
}
[/CODE]

Would this work?
<section class="prodList">
<?php
$categories = array("All","Clothes","Gadgets","Games");
foreach($categories as $cat){
/** Since you know it should repeat four times, why not echo 4 times? */
echo "<h2> new cat: ".$cat."</h2>";
echo "<div style='display:inline-block;padding:5px'>". $cat . "</div>";
echo "<div style='display:inline-block;padding:5px'>". $cat . "</div>";
echo "<div style='display:inline-block;padding:5px'>". $cat . "</div>";
?>
<!-- You don't have to echo plain HTML -->
<div class='viewerWishlistProdContainer'>
<div class='prodImageContainer'>
</div>
</div>
<p>
<button class='sortBtns' onClick='alert(\'See all V'\)'>See all V</button>
</p>
<?php } /** closing the foreach block */ ?>
</section>

Related

Use PHP foreach loop to display data in many html div tags

I have the following data and would like to display it in different containers in html.
Name Price Difference Signal
CA.PA 15.85 3.5609257364073 MACD
AZN.ST 896 3.4881049471963 MACD
AMGN 258.57 1.6391533819031 SMA 50/200
The containers are winner_1. As of right now the first winner_1 display the last Name from the above table.
How can I get it to say CA.PA in the first winner_1, and AZN.ST in the second winner_1, and AMGN in the last winner_1.
<div class="overview">
<h1>Winners</h1>
<div class="winner">
<?php
foreach ($res_winners_weekly as $r){
$name = $r["Name"];
$Price = $r['Price'];
$percent_diff = $r['Difference'];
$signal = $r['Signal'];
}
?>
<div class="winner_1">
<?php echo $name; ?>
</div>
<div class="winner_1">
<?php echo $name +1; ?>
</div>
<div class="winner_1">
</div>
</div>
</div>
The page can be seen here:
https://signal-invest.com/markets-today/
One option is generated div tags using php:
<div class="overview">
<h1>Winners</h1>
<div class="winner">
<?php
foreach ($res_winners_weekly as $r) {
$name = $r["Name"];
$Price = $r['Price'];
$percent_diff = $r['Difference'];
$signal = $r['Signal'];
echo "<div class='winner_1'>";
echo "<a href='#'>{$name}</a>";
echo "</div>";
}
?>
</div>
</div>
You should see following logic and try doing this way. Hopefully your problem will be resolved.
<div class = "overview">
<h1>Winners</h1>
<div class = "winner">
<?php
foreach ($res_winners_weekly as $r) {
$name = $r["Name"];
$Price = $r['Price'];
$percent_diff = $r['Difference'];
$signal = $r['Signal'];
echo "<div class='winner_1'><a href='#'> $name </a></div>";
}
?>
</div>
</div>

While Loop displays arguments inside the first argument

I have a while loop created to display all my wordpress posts. The issue is that all the posts (except the first) appear inside the first post.
I've check my div structures and I couldn't find any issues.
The loop is working, but the div isn't showing in the right place.
<div class="slider-vertical">
<!-- This is the main loop for the posts -->
<?php
$count = 0;
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$count++;
// Variabled for the specific fields (color, 3D objects and so on...)
$fond_couleur = get_field('fond_de_couleur_hex');
$visuel_3D = get_field('source_iframe_3d');
$visuel_3D_2 = get_field('source_iframe_3d_2');
// get_template_part( 'template-parts/content', 'portfolio' );
$content = get_the_content();
$content = apply_filters( 'the_content', $content );
$content = str_replace( ']]>', ']]>', $content );
$gallerieArray = get_field('image_galerie');
$title = get_the_title($post);
?>
<!-- HTML structure for the posts - this is displayed, but only the first one is at the right place -->
<?php
echo '<div class="post-numero';
if($count == 1){
echo ' actif';
}
echo '">';
?>
<!-- DIV that contains the 3D object -->
<div class="visuel-3d" style="background:<?php echo $fond_couleur;?>;">
<!-- Injecting the 3D Object via an iframe -->
<div class="slider-horizontal">
<?php echo '<span class="post-horizontal actif">'. $visuel_3D .'</span>';?>
<?php if($visuel_3D_2){
echo '<span class="post-horizontal">'. $visuel_3D_2 .'</span>';
} ?>
</div>
<h2 class="titrePost"><?php echo $title; ?></h2>
</div>
<!-- Cross used to close the rightside menu -->
<span class="arrow-right-sidebar">x</span>
<!-- HTML structure for the rightside menu -->
<div class="right-sidebar-content foo">
<div class="right-top">
<h2 style="text-align: center;"><?php echo $title; ?></h2>
</div>
<div class="right-bottom">
<div><?php echo $content ?></div><!-- That is where the next posts of the while loop get printed -->
<div class="gallerie-sidebar-full">
<?php // loop for the image gallery at the bottom of the rightside menu
if ($gallerieArray == true){
foreach($gallerieArray as $key => $val){
$gallerieImages[] = $val["url"];
}
$idg = 0;
foreach ($gallerieImages as $val){
echo '<img id="id-'. $title .'-'. $idg .'" class="gallerie-sidebar" src="'. $val .'">';
$idg += 1;
}
}
?>
</div>
</div>
</div>
</div>
<?php
endwhile;
?>
</div>
What is expected is 4 different posts inside the "slider-vertical" div displayed at the same level in the HTML structure.
The actual result is the first post at the correct level and then the next posts 2 levels deeper inside the first post.
this kind of problem occurs when there is a not properly closed HTML tag on the first execution of the loop, try to use a short statement syntax
echo '<div class="post-numero'. (($count == 1)? ' actif' : '').'">;
check also the content printed by <?php echo $content ?> of the first post, may contains an open HTML tag.
You can easily check the generated code using the souce view (CTRL+U) in Firefox that highlights in red the wrong HTML closing tags

Active button error

how are you? I'm having a problem with a program I'm modifying.
is a series site I almost managed to solve everything else I arrived at a point that is difficult to identify the problem.
In the page of the series to be displayed the seasons appear and also the episodes appear.
The buttons of the first episode of each season appear highlighted as if they were being watched, and when I click on an episode everyone is unmarked and what I clicked becomes active.
I want the only thing to stay active is episode 1 of the first season which is what is being displayed on screen and the other first episodes are turned off.
the problem is in the following line:
<?php
if($episode['stream_key']==$current_key){
echo 'btn-success';
} else {
if($current_key=='000000' && $i=='1'){
echo 'btn-success';
}else{
echo 'btn-default';
}
}
?>
the line below is to understand the context:
<div class="row">
<div class="col-md-12 m-t-10 m-b-10">
<?php
$this->db->order_by('seasons_id', "ASC");
$seasons = $this->db->get_where('seasons',array('videos_id'=>$watch_videos->videos_id))->result_array();
foreach ($seasons as $season):
?>
<?php if($this->common_model->get_num_episodes_by_seasons_id($season['seasons_id']) > 0): ?>
<div class="season">
<p class="btn btn-inline text-uppercase" style="font-size: 12px;color: #055b86">TEMP: <?php echo $season['seasons_name']; ?> | EP: </p>
<?php
$this->db->group_by('seasons_id');
$this->db->order_by('seasons_id', "ASC");
$this->db->group_by('episodes_id');
$this->db->order_by('episodes_id', "ASC");
$episodes = $this->db->get_where('episodes',array('videos_id'=>$watch_videos->videos_id,'seasons_id'=> $season['seasons_id']))->result_array();
$i=0;
$current_key = '000000';
if(isset($_GET['key']))
$current_key = $_GET['key'];
foreach($episodes as $episode):
$i++;
?>
<?php echo $episode['episodes_name']; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>

Combining php loop and count - Wordpress ACF

I wondered if anyone could help me combine two blocks of code I have. I have one block looping though items and the start of another block showing a count and hopefully enabling me to display the items looping through in rows by adding a div around them every two items... Heres the first bit of code, the loop:
<?php if(get_field('areas')): ?>
<?php while(has_sub_field('areas')): ?>
<div class="single-area-item six columns">
<p> <img src="<?php the_sub_field('area_icon'); ?>" style="width:100%;"> <p>
<h4> <?php the_sub_field('area_title'); ?> </h4>
<p> <?php the_sub_field('area_info'); ?> <p>
</div>
<?php endwhile; ?>
<?php endif; ?>
I'm using Advance Custom Fields for Wordpress and this is pulling through repeater fields... this displays them just one after the other.
Here's the code I have found to hopefully display them in rows.
<?php
$num = 1;
foreach ( $terms as $term ) {
if($num%2) {
echo '<div class="area-row">';
}
// Other Code
if($num %2) {
echo '</div>';
}
$num++
}
?>
I would like to display them in rows of two...
ONE TWO
THREE FOUR
FIVE SIX
Etc...
So, Im guessing I need to combine the code somehow... I currently have this: but it doesn't seem to work:
<?php
$num = 1;
foreach ( $terms as $term ) {
if($num%2) {
echo '<div class="area-row">';
}
if(get_field('areas')): ?>
<?php while(has_sub_field('areas')): ?>
<div class="single-area-item six columns">
<p> <img src="<?php the_sub_field('area_icon'); ?>" style="width:100%;"> <p>
<h4> <?php the_sub_field('area_title'); ?> </h4>
<p> <?php the_sub_field('area_info'); ?> <p>
</div>
<?php endwhile; ?>
<?php endif; ?>
if($num %2) {
echo '</div>';
}
$num++
}
?>
Okay so it looks like there was a couple of simple issues with this, you had closed the php tag after your if statment and then continued to write php without reopening the php tags. Also there is a slight logic error with the if($num%2) statements as one of these needs to be if, the other needs to be if not, so that the alternate.
Give this code a try and let me know how you get on:
<?php
if(get_field('areas')):
$num = 1;
?>
<?php while(has_sub_field('areas')):
if($num%2) {
echo '<div class="area-row">';
} ?>
<div class="single-area-item six columns">
<p> <img src="<?php the_sub_field('area_icon'); ?>" style="width:100%;"> <p>
<h4> <?php the_sub_field('area_title'); ?> </h4>
<p> <?php the_sub_field('area_info'); ?> <p>
</div>
<?php
if(!$num%2) {
echo '</div>';
}
$num++
endwhile; ?>
<?php endif; ?>
The main reason behind this question was for me to be able to target the third item of the looped through items, as it had padding on it that was breaking the rows that I needed to remove.
I have since found another solution that seems to be working.
By using the nth-child element, I have been able to target and remove the padding on every third item that's looped through - fixing the issue.
.single-area-item:nth-child(3n+3) {
margin-left: 0;
}
This is for rows or 2 items, if it were rows of 3 or 4 then it would need to target every 4th or 5th item respectively.

PDO MySQL product loop

Im a real beginner when it comes to queries and PDO, i need some assistance in a project i am busy with. What i want to accomplish is to display products from the database. However the template style i am using forces me to show 3 products per row, is there a way to show 3 products per row and loop the code once there is more than 3 (if there is 5 products, the first 3 will display in the first row, and the rest in the second).
Here is the template i am using, note the div class "top-box", this forces that only 3 products can be shown per row.
<div class="top-box">
<?php
$sql = "SELECT * FROM _products WHERE category = '$cat'";
$result = dbConnect()->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
$cols = $result->columnCount(); // Number of returned columns
// Generate ADS Feed for each ROW
foreach($result as $row) {
echo '<div class="col_1_of_3 span_1_of_3">
<a href="product.php?i=' . $row['model'] . '">
<div class="inner_content clearfix">
<div class="product_image">
<img src="images/' . $row['model'] . '.jpg" alt=""/>
</div>
<div class="price">
<div class="cart-left">
<p class="title">' . $row['name'] . '</p>
</div>
<div class="clear"></div>
</div>
</div>
</a>
</div>';
}
} else {
echo "<p>No products available at this moment, contact us for more information!</p>";
}
?>
<div class="clear"></div>
</div>
You can solve it like this:
<?php
if ($counter % 3 == 0 && $counter!=$total_row_fetched) {
echo '<div class="clear"></div>';
echo '</div>';
echo '<div class="top-box">';
}
if($counter==$total_row_fetched){
echo '<div class="clear"></div>';
echo '</div>'; // it will close the last open div
}
++$counter;
?>
You can use a count variable inside your products foreach-loop. Every three products you can close the top-box and open a new one (This is an assumption as I don't know exactly how your styles work).
At the end of the foreach-loop:
if ($count != 0 && $count % 3 == 0) {
echo '<div class="clear"></div>';
echo '</div>'; // close last .top-box
echo '<div class="top-box">';
}
++$count;
I don't see how your question is connected to PDO. Keep in mind that using unescaped variables inside a query is potentially dangerous. Have a look here for some help: https://stackoverflow.com/a/60496/2516377
Add a counter and use % arithmetic operator to calculate column number.
$counter=0;
foreach (...) {
$column_number=$counter % 3;
$counter++;
}

Categories