More efficient way of using foreach? - php

I'm using a php foreach loop to pull data from database to generate a header but as I know there is only one result there must be a more efficient way?
<?php
foreach ($category as $value)
{
echo "<header style='background-color:#".$value->CategoryColor."'>";
echo "<div class='container'>";
echo "<div class='row'>";
echo "<div class='col-lg-12'>";
echo "<div class='page-intro'>";
echo "<span class='title'><i class='fa ".$value->CategoryIcon."'></i> ".$value->CategoryTitle."</span>";
echo "<span class='descriptive'>".$value->CategoryDescription."</span>";
}
?>
This is using CodeIgniter MVC

<?php
foreach ($category->result() as $value): ?>
<header style="background-color:#<?= $value->CategoryColor; ?>">
<div class='container'>
<div class='row'>
<div class='col-lg-12'>
<div class='page-intro'>
<span class='title'><i class='fa <?= $value->CategoryIcon; ?>'></i> <?= $value->CategoryTitle; ?></span>
<span class='descriptive'><?= $value->CategoryDescription; ?></span>
}
<?php endforeach;?>
?>

Related

Append html element in php like jQuery append

I know jQuery append element, but I want to know is there any way so that I can append 50 similar elements using php with some loop so something else, The elements I want to append 50 times are given here,
<div class='test'>
<span class='<?php echo $result[0]->cc1;?>'><?php echo $result[0]->dd1;?></span>
</div>
<div class='test'>
<span class='<?php echo $result[0]->cc2;?>'><?php echo $result[0]->dd2;?></span>
</div>
<div class='test'>
<span class='<?php echo $result[0]->cc3;?>'><?php echo $result[0]->dd3;?></span>
</div>
<div class='test'>
<span class='<?php echo $result[0]->cc4;?>'><?php echo $result[0]->dd4;?></span>
</div>
// and so on.. up to 50.
Tried this but not working,
<?php for ($i=0; $i <50; $i++) : ?> <span class='<?php echo $result[0]->cc'+i+';?>'><?php echo $result[0]->dd'+i+';?></span> <?php endfor; ?>
Create a loop
Then using the $result[0]->{'cc'.$i} syntax address all your properties
for( $i=1; $i<51; $i++) :
?>
<div class='test'>
<span class='<?php echo $result[0]->{'cc'.$i};?>'><?php echo $result[0]->{'dd'.$i};?></span>
</div>
<?php
endfor;

How to convert foreach loop to while loop?

I am currently using a foreach loop to display the data from my database on my website but have just tried to include pagination which is using a while loop.
<?php
foreach ($posts as $post): ?>
<div class="post clearfix">
<img src="<?php echo BASE_URL . '/assets/images/' . $post['image']; ?>" alt="" class="post-image">
<div class="post-preview">
<h2><?php echo $post['title']; ?></h2>
<i class="far fa-user"> <?php echo $post['username']; ?></i>
<i class="far fa-calendar"> <?php echo date('F j, Y', strtotime($post['created_at'])); ?></i>
<p class="preview-text">
<?php echo html_entity_decode(substr($post['excerpt'], 0, 150) . '...'); ?>
</p>
Read More
</div>
</div>
<?php endforeach; ?>
while ($row = mysqli_fetch_array($result)) {
}
?>
How do I go about transferring the data here/incorporating them both together into the while loop so that the pagination works smoothly and the data remains displayed as it currently is? Thanks
To convert foreach to while loop. Simply,
Note: if "$posts" is an object array
try this below
<?php
$i=0;
while($i < sizeof($posts)){
$post=$posts[$i++]; ?>
//use $post object in your code
//something like $post['image']
<?php }?>

Joomla Database values fetch in custom module

I have created a module in Joomla which will fetch the values from Joomla database table and show in a bootstrap HTML carousal. fetching part is working well but whenever I put the PHP code into Html code where I want those fields to display the carousel is not working. any help will be appreciated. below is my full page code (tmpl/dafault.php)
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/afterglowplayer#1.x"></script>
<?php
defined('_JEXEC') or die;
?>
<?php
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true);
$query->select("*")
->from("tkps5_spotlightamsw_spotlight");
$db->setQuery($query);
$row = $db->loadObjectList();
}
catch (exception $e) { echo $e; }
?>
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-md-6">
<h2 class="block-title1">xyz text</h2>
<p class=" "><a class="button subbutton btn btn-border1" href="#">More info</a></p>
</div>
<div class="col-md-6">
<h2 class="block-title1">Spotlight</h2>
<!-- Wrapper for slides -->
<script>
$(document).ready(function() {
//Enable swiping...
$(".carousel-inner").swipe( {
//Generic swipe handler for all directions
swipeLeft:function(event, direction, distance, duration, fingerCount) {
$(this).parent().carousel('prev');
},
swipeRight: function() {
$(this).parent().carousel('next');
},
//Default is 75px, set to 0 for demo so any distance triggers swipe
threshold:0
});
});
</script>
<?php foreach ($row as $row): ?>
<?php
$fetured_spotlight = $row->featured_spotlight;
$name = $row->name;
$modified_date = $row->modified;
if($fetured_spotlight == 1 )
{
echo "<div id='myCarousel' class='carousel slide' data-ride='carousel' data-touch='true'> ";
echo " <div class='carousel-inner'>";
echo substr($modified_date,0 , 10);
echo "<div class='item '>";
echo "<img src='".$row->thumbnailimage."' alt='".$name."'>";
echo "<div class='carousel-caption1'>";
echo "<p><strong>".$name."</strong></p>";
echo "</div>";
echo "</div>";
//echo $row->name;
echo " <a class='left carousel-control' href='#myCarousel' data-slide='prev'>";
echo " <span class='glyphicon glyphicon-chevron-left'></span>";
echo " <span class='sr-only'>Previous</span>";
echo " </a>";
echo " <a class='right carousel-control' href='#myCarousel' data-slide='next'>";
echo " <span class='glyphicon glyphicon-chevron-right'></span>";
echo " <span class='sr-only'>Next</span>";
echo " </a>";
echo "</div>";
}
?>
<?php endforeach; ?>
<!-- Left and right controls
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>-->
<p class="align-right"><a class="button subbutton btn btn-border1" href="flame-spotlight">VIEW ALL</a></p>
</div>
</div>
</div>
</div>
Finally i got the answer where i was not assigning the "active" class to first slider image. so below is my working code .. just posting for loop rest of the code is same..
<?php foreach ($row as $key=>$row): ?>
<?php
$fetured_spotlight = $row->featured_spotlight;
$name = $row->name;
if($fetured_spotlight == 1 )
{
?>
<div class='item <?php echo ($key == 0) ? "active" : ""; ?>'>
<?php
echo "<img src='".$row->thumbnailimage."' alt='".$name."'>";
echo "<div class='carousel-caption1'>";
echo "<p><strong>".$name."</strong></p>";
echo "</div>";
//echo $row->name;
echo "<br />";
}
?>
</div>
<?php endforeach; ?>

New containing div after every 3 records

I would like to create a new containing <div> after 3 results, using PDO result loop.
For my self-study-project I have to made a product page with bootstrap and after every 3rd record I have to make a new row and show again 3 col-md-4's, etc, etc.
Now I have this as my code:
<div class="row">
<?php
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
?>
<div class="col-md-4">
<div class="product">
<div class="title"><?php echo $row->pname ?></div>
<div class="img"><img
src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/>
</div>
<div class="vijftien"></div>
<div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong></div>
<div class="vijf"></div>
<div class="other"></div>
<div class="row">
<div class="col-md-6">
<div class="price"><?php echo $row->pprice ?></div>
</div>
<div class="col-md-6">
<div class="order">
<button class="log_in" id="doLogin">Meer informatie</button>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
I have visited and studied other questions but I do not really get the idea of how they are doing it and how I can implement the correct method into my code.
As tadman stated in the comment under your question. The best approach should use a modulus operator (%) with 3.
Place your separating condition at the start of each iteration. (Demo)
Like this:
$x=0; // I prefer to increment starting from zero.
// This way I can use the same method inside a foreach loop on
// zero-indexed arrays, leveraging the keys, and omit the `++` line.
echo "<div class=\"row\">";
foreach($rows as $row){
if($x!=0 && $x%3==0){ // if not first iteration and iteration divided by 3 has no remainder...
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "</div>";
This will create:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
Late Edit, here are a couple of other methods for similar situations which will provide the same result:
foreach(array_chunk($rows,3) as $a){
echo "<div class=\"row\"><div>",implode('</div><div>',$a),"</div></div>\n";
}
or
foreach ($rows as $i=>$v){
if($i%3==0){
if($i!=0){
echo "</div>\n";
}
echo "<div class=\"row\">";
}
echo "<div>$v</div>";
}
echo "</div>";
To clarify what NOT to do...
Sinan Ulker's answer will lead to an unwanted result depending on the size of your result array.
Here is a generalized example to expose the issue:
Using this input array to represent your pdo results:
$rows=["one","two","three","four","five","six"];
Sinan's condition at the end of each iteration:
$i=1;
echo "<div class=\"row\">";
foreach($rows as $row){
echo "<div>$row</div>";
if($i%3==0)echo "</div>\n<div class='row'>"; // 6%3==0 and that's not good here
// 6%3==0 and will echo the close/open line after the content to create an empty, unwanted dom element
$i++;
}
echo "</div>\n\n";
Will create this:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
<div class='row'></div> //<--- this extra element is not good
You need to add a new closure tag and open new one every 3th iteration.
<div class="row">
<?php
$sql = "SELECT * FROM products";
$stmt = $conn->query($sql);
$stmt->execute();
$i=1;
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
?>
<div class="col-md-4">
<div class="product">
<div class="title"><?php echo $row->pname ?></div>
<div class="img"><img
src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/>
</div>
<div class="vijftien"></div>
<div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong>
</div>
<div class="vijf"></div>
<div class="other"></div>
<div class="row">
<div class="col-md-6">
<div class="price"><?php echo $row->pprice ?></div>
</div>
<div class="col-md-6">
<div class="order">
<button class="log_in" id="doLogin">Meer informatie</button>
</div>
</div>
</div>
</div>
</div>
<?php
if($i%3==0)echo "</div><div class='row'>";
$i++;
} ?>
$x = 0;
echo "";
foreach($rows as $row)
{
/* added one more condition for removing empty div.... */
if ($x != 0 && $x % 3 == 0 && $x < count($rows))
{
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "";

Create outer div if counter is divisible by 4

I have a problem looping my html tags. My goal is to enclose every 4 div with class "item" inside the class of "item-wrap". So far here's my code:
$speakers will return 8 rows so "item-wrap" class will be display twice with 4 "item" class inside
<?php
$speaker_ctr = 0;
if(count($speakers) > 0){
?>
<div class="item-wrap">
<?php foreach($speakers as $speaker){ ?>
<div class="item"> <img class="lazy" data-lazy-src="<?php echo $speaker['imagepath']; ?>" />
<h5 class="txt-18 bold-font text-uppercase no-mbt mt-20"><?php echo $speaker['name']; ?></h3>
<p class="no-mn"><?php echo $speaker['position']; ?></p>
<?php echo $speaker['company']; ?>
</div>
<?php } ?>
</div>
<?php
$speaker_ctr++;
}
?>
Try below code:-
<?php
if(count($speakers) > 0){
for($i=0;$i<=count($speakers);$i++){
if($i%4==0){
echo '<div class="item-wrap">';
}
?>
<div class="item"> <img class="lazy" data-lazy-src="<?php echo $speakers[$i]['imagepath']; ?>" />
<h5 class="txt-18 bold-font text-uppercase no-mbt mt-20"><?php echo $speakers[$i]['name']; ?></h3>
<p class="no-mn"><?php echo $speakers[$i]['position']; ?></p>
<?php echo $speakers[$i]['company']; ?>
</div>
<?php
if($i%4==0){
echo '</div>';
}
}
}
Try with -
$speaker_ctr = 0;
if(count($speakers) > 0){
?>
<div class="item-wrap">
<?php
foreach($speakers as $speaker){
$speaker_ctr++; // increment
?>
<div class="item"> <img class="lazy" data-lazy-src="<?php echo $speaker['imagepath']; ?>" />
<h5 class="txt-18 bold-font text-uppercase no-mbt mt-20"><?php echo $speaker['name']; ?></h3>
<p class="no-mn"><?php echo $speaker['position']; ?></p>
<?php echo $speaker['company']; ?>
</div>
<?php
// print if divisible by 4
// every 4th element
if($speaker_ctr%4 == 0 && $speaker_ctr != count($speakers)) {
echo "</div><div class='item-wrap'>";
}
}
?>
</div>
<?php
}

Categories