Search code examples
phpmysqlmagentomagento-1.5

How to get 3 random rows each time page is refreshed?


I have the following code:

<?php $i = 0; ?>

    <?php foreach ($this->getMyCollection() as $faqItem): ?>
        <a class="anchor" href="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) ?>faq#<?php echo $i ?>"><?php echo $this->htmlEscape($faqItem->getQuestion()) ?></a><br>
    <?php
        $i++;
        if($i>2)break;
    ?>
    <?php endforeach; ?>

But what I want to show is three different rows each time a page is refreshed. How do I do that?


Solution

  • Try this:

    With array_rand you can pass an array, and define the number of results you want. It will return the given number of keys you want to use.

    <?php $i = 0;
    $items = $this->getMyCollection();
    $keys = array_rand($items, 3);
    foreach ($keys as $key): 
    {
    
        $faqItem = $items[$key];
    ?>
    
        <a class="anchor" href="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) ?>faq#<?php echo $i ?>"><?php echo $this->htmlEscape($faqItem->getQuestion()) ?></a><br>
    <?php
        $i++;
    } ?>
    

    Or option 2, use the Shuffle function:

    <?php foreach (shuffle($this->getMyCollection()) as $faqItem): ?>
        <a class="anchor" href="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) ?>faq#<?php echo $i ?>"><?php echo $this->htmlEscape($faqItem->getQuestion()) ?></a><br>
    <?php
        $i++;
        if($i>2)break;
    ?>
    <?php endforeach; ?>