简体   繁体   中英

Looping Through a ForEach Multidimentional array 5 times only

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>

<? } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM