Looping Through a ForEach Multidimentional array 5 times only - php

I have a simple problem which I simply can't find the answer too. I have a multi-dimentional array coming from my Joomla which currently shows all the blog articles on my website. I only want to show the most recent 5.
Here's the code:
<?php
foreach($list as $item) {
?>
<li>
<a href="<?php echo $item->link; ?>" class="latestnews<?php echo $params->get('moduleclass_sfx'); ?>">
<?php echo $item->text; ?></a>
</li>
}
?>
I've seen a few similar posts but none of them seem to do what I'm looking for. Hopefully a simple one to the trained eye. Please help me on my day off! :-)
Newbie :-(

You can use array_slice() to slice off the first 5, assuming they are ordered from newest to oldest.
<?php
foreach(array_slice($list, 0, 5) as $item) {
?>
If they are ordered the opposite way, use array_slice($list, -5).

Either you use array_slice() to get only the part of the array that you need, or you can use a counter in your loop and break when you reach you desired number.
As array_slice() is displayed in another answer, I'll just give you an example using a counter and break:
<?php
$i = 0;
foreach($list as $item) {
if ($i > 4)
break;
$i++;
?>
<li>
<a href="<?php echo $item->link; ?>" class="latestnews<?php echo $params->get('moduleclass_sfx'); ?>">
<?php echo $item->text; ?></a>
</li>
<? } ?>

Related

Two items per foreach loop

Apologies if this has already been asked (I cannot find an answer) but I am using PHP and I am building a slider, but would like two images per slide, not one. So, in theory the foreach() needs to include two per each.
An example of the setup is as follows:
<?php foreach ($page->images as $image) : ?>
<img src="<?php echo $image->url; ?>"/>
<?php endforeach; ?>
I was thinking I could do something like a count...
<?php $index = 0; foreach ($page->images as $image) : ?>
<img src="<?php echo $image->url; ?>"/>
<?php $index++; ?>
<?php if ( $index % 2 == 0 && $index !=count($page->images) ) : ?>
<li></li>
<?php endif; ?>
<?php endforeach; ?>
But I got a little confused as this would insert something every 2... not include two of whatever the foreach loop is fetching at once.
Hope this makes sense and thanks in advance
Why so complicated? Use a simple for loop instead:
<?php for ($i=0; $i<count($page->images)-1; $i+=2) { ?>
<img src="<?php echo $page->images[$i]->url; ?>"/>
<img src="<?php echo $page->images[$i+1]->url; ?>"/>
<?php } ?>
Or even more elegant, a do/while loop:
<?php $i=0; do { ?>
<img src="<?php echo $page->images[$i++]->url; ?>"/>
<img src="<?php echo $page->images[$i++]->url; ?>"/>
<?php } while ($i<count($page->images)) ?>
Compared to using a foreach loop these approaches have another advantage: you do not create copies of all objects. This can make a huge difference if those objects are non-trivial.
Okay, I managed to work this out... hopefully it will help.
<div class="each-slide">
<?php $index = 0; foreach ($page->images as $image) : ?>
<img src="<?php echo $image->url; ?>"/>
<?php $index++; ?>
<?php if ( $index % 2 == 0 && $index !=count($page->images) ) : ?>
</div><div class="each-slide">
<?php endif; ?>
<?php endforeach; ?>
</div>

How to run a code within a loop but only show every 3 times it runs [duplicate]

This question already has answers here:
PHP: How do you determine every Nth iteration of a loop?
(8 answers)
Closed 8 years ago.
I have a loop running for wordpress that calls category images
<ul>
<?php foreach (get_terms('your_taxonomy') as $cat) : ?>
<li>
<img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" />
<?php echo $cat->name; ?>
</li>
<?php endforeach; ?>
</ul>
Now the trick is (don't know if its possible) I want that after every 3 images a div to show for adwords. I but I don't want every other one as I believe it will do if I added it part of the wordpress loop... Is there a way to accomplish this?
Just use a counter, like this:
<ul>
<?php
$i=0;
foreach (get_terms('your_taxonomy') as $cat) :
?>
<li>
<img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" />
<?php echo $cat->name; ?>
</li>
<?php
$i++;
if(!$i%3) {
echo '<div>Here is your div</div>';
}
endforeach;
?>
</ul>

how to use call on multiple tables in a php for each loop

I'd like to display results from two tables in my MYSQL database using the for each loop. Currently I have split both tables into two separate loops like this:
<?php
$i = 0;
foreach (array_reverse ($articles) as $article){?>
<div class="greyvertical midtopmargin item leftpadding rightpadding">
<a href="article.php?id=<?php echo $article['article_id']; ?>"><img src="../lifestyle/photos/articles/<?php echo $article['photo_folder']; ?>/<?php echo $article['photo_1']; ?>" alt="item">
<h5 class="whitetext text2 extrabold smalltoppadding leftpadding"><?php echo $article['article_title']; ?></h5></a>
<p class="meta whitetext leftpadding smalltoppadding">
<?php echo $article['article_summary']; ?></p>
READ ME
</div>
<?php if (++$i == 5) break;
} ?>
<?php
$i = 0;
foreach (array_reverse ($posts) as $post){?>
<div class="greyvertical midtopmargin item leftpadding rightpadding">
<a href="post.php?id=<?php echo $post['post_id']; ?>"><img src="../lifestyle/photos/blog/<?php echo $post['photo_folder']; ?>/<?php echo $post['photo_bg']; ?>" alt="item">
<h5 class="whitetext extrabold text2 leftpadding smalltoppadding"><?php echo $post['post_title']; ?></h5></a>
<p class="meta leftpadding whitetext smalltoppadding">
<?php echo $post['post_summary']; ?></p>
READ ME
</div>
<?php if (++$i == 5) break;
} ?>
As you can see they are almost identical with slight differences but I am completely stuck on how to combine the two without them being separate as it is now. Could anyone let me know in layman's terms how to combine the two loops into one? I.e I want to combine the articles and posts tables so they will be displayed as one rather than separately. thanks in advance guys.
The comments made on your question make sense and you should take them into account, but there is a way of iterating over two arrays at once by using PHP's MultipleIterator. Here is a much simplified example of how this could work for you:-
$articles = array('article 1','article 2','article 3');
$posts = array('post 1', 'post 2', 'post 3');
$iterator1 = new ArrayIterator($articles);
$iterator2 = new ArrayIterator($posts);
$multiIterator = new MultipleIterator();
$multiIterator->attachIterator($iterator1);
$multiIterator->attachIterator($iterator2);
foreach($multiIterator as $combinedArray){
echo $combinedArray[0] . "<br/>\n";
echo $combinedArray[1] . "<br/>\n";
}
Output:-
article 1
post 1
article 2
post 2
article 3
post 3

Offset PHP array results

I am looking to offset a group of PHP array results to create multiple rows of data.
For example, the first row will contain the first four array results, with the second row displaying results 5-8 and the third row containing results 9-12.
Currently, I am printing out all 12 in one list, however I'd like a bit more display control (i.e. ordering the results into columns which I can style independent of each), hence why I'd like to offset the results.
My current PHP is below:
<?php
if (empty($tmdb_cast['cast'])) {
} else {?>
<section class="cast">
<p class="title">Cast</p>
<ul class="section_body"><?php
foreach($tmdb_cast['cast'] as $key => $castMember){
if ($key < 12) {?>
<li class="actor_instance clearfix"><?php
if ($castMember['profile_path'] != '') {?>
<img src="http://cf2.imgobject.com/t/p/w45<?php echo $castMember['profile_path']; ?>" class="actor_image pull-left" alt="<?php echo $castMember['name']; ?>" title="<?php echo $castMember['name']; ?>" /><?php
} else {?>
<img src="assets/images/castpic_unavailable.png" class="actor_image pull-left" alt="No image available" title="No image available" /><?php
}?>
<p class="actor"><?php echo $castMember['character']; ?> - <?php echo $castMember['name']; ?></p>
</li><?php
}
}?>
<div class="morecast pull-right">[...view all cast]</div>
</ul>
</section><?php
}?>
P.S. Apologies for how I've formatted the code in the above block - I'm still not 100% sure how to make it look "nice" on StackOverflow.
Use array_chunk to break a single dimension array into a 2D array. Then you can loop through each chunk, and then each result, to get that "offset" effect between them.
$chunks = array_chunk($tmdb_cast['cast'], 4); // 4 here, is the number you want each group to have
foreach($chunks as $key => $chunk)
{
foreach($chunk as $castMember)
{
//display castMember here
}
// add code between groups of 4 cast members here
}
First: mixing php and html this way is a very bad habbit... one day you will have to maintain your code and that day you will vomit all over your desk because you mixed different languages in one file...
That being said..
and without creating a new array:
foreach($tmdb_cast['cast'] as $key => $castMember)
{
if ($key < 12)
{
// your code goes here
// if key is 3, or 7 the code below will close the listcontainer and open a new one...
if( ($key+1)%4 == 0 AND $key <11)
echo '</ul> <ul class="section_body">';
}
}
Also replace this:
if (empty($tmdb_cast['cast']))
{
}
else {
with this:
if (!empty($tmdb_cast['cast']))
{
I'm not entirely sure what you're looking for but here's how I would format your code. Alternative syntax for 'if' is a little more readable, and the use of for loops instead of a foreach will give you the control over row numbers you say you're looking for.
<?php if( ! empty($tmdb_cast['cast'])): ?>
<section class="cast">
<p class="title">Cast</p>
<ul class="section_body">
<?php
for($i = 0; $i < 12; $i++):
$castMember = $tmdb_cast['cast'][$i];
?>
<li class="actor_instance clearfix">
<?php if($castMember['profile_path'] != ''): ?>
<img src="http://cf2.imgobject.com/t/p/w45<?php echo $castMember['profile_path']; ?>" class="actor_image pull-left" alt="<?php echo $castMember['name']; ?>" title="<?php echo $castMember['name']; ?>" />
<?php else: ?>
<img src="assets/images/castpic_unavailable.png" class="actor_image pull-left" alt="No image available" title="No image available" />
<?php endif; ?>
<p class="actor"><?php echo $castMember['character']; ?> - <?php echo $castMember['name']; ?></p>
</li>
<?php endfor; ?>
<div class="morecast pull-right">[...view all cast]</div>
</ul>
</section>
<?php endif; ?>

PHP end div after X amount of divs and start new one

I am trying to achieve to show 4 divs on 1 line and after those 4 divs it should automatically end the line and continue with the new line of 4 divs. What I have right now is;
<?php
// Make sure to just show items if there are any.
if ($is_empty)
{
echo 'There are no products found.';
}
else
{
// Start counting the products.
$i = 1;
// List up all products.
foreach ($results as $item):
// Count up the productcount.
$i++;
?>
<a href="<?php echo base_url(); ?>product/<?php echo $item['product_id']."-".$item['name_clean']; ?>.html">
<?php echo $item['name']; ?>
</a>
<?php
endforeach;
}
?>
So like, if $i = 4, 8, 12 etc etc, cut off the line (maybe add a div that's holding those 4?) and start a new one.
Is that possible? I know it is with tables, as I found here PHP: End and start a new <tr> after 6 rows
Thanks.
Use modulus (%) to calculate every 4th element.
<?php
// Start counting the products.
$i = 0;
// List up all products.
foreach ($results as $item):
// Count up the productcount.
$i++;
?>
<a href="<?php echo base_url(); ?>product/<?php echo $item['product_id']."-".$item['name_clean']; ?>.html">
<?php echo $item['name']; ?>
</a>
<?php
if($i%4 == 0):
?>
<br />
<?php
endif;
?>
endforeach;
?>

Categories