2013-01-21 73 views
0

下面的代碼只是顯示「類別12」中的所有子類別的類別縮略圖,我正在尋找一種方法將此數字限制爲6個類別,並將其作爲這些類別的隨機選擇。Randomise&limit在主頁上的類別縮略圖magento

<ul class="brand_list"> 
     <?php $media = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?> 
     <?php $children = Mage::getModel('catalog/category')->getCategories(12); ?> 
     <?php foreach ($children as $category): ?> 
      <?php $category = Mage::getModel('catalog/category')->load($category->getId()); ?> 
      <li class="span3"> 
       <a href="<?php echo $category->getUrl(); ?>"> 
        <img alt="<?php echo $category->getName(); ?>" src="<?php echo $media; ?>/catalog/category/<?php echo $category->getThumbnail(); ?>" /> 
       </a> 
      </li> 
     <?php endforeach; ?> 
    </ul> 

我以前使用過類似的代碼使用的代碼如下兩件產品:

<?php $collection->getSelect()->order('rand()'); ?> 

<?php $_columnCount = $this->getColumnCount(); ?> 
<?php $i=0; foreach ($collection->getItems() as $category): if($i==6){break;}?> 
<?php if ($i++%$_columnCount==0): ?> 
<?php endif ?> 

我試圖重新編碼,使之適合的類別大拇指,但我似乎不被其任何喜悅。

回答

2

您的問題的解決方案是波紋管。我不會使用mysql rand()函數,因爲它很慢。

<ul class="brand_list"> 
    <?php 
    $media = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); 
    $parentCategory = Mage::getModel('catalog/category')->load(12); 
    $children = Mage::getModel('catalog/category') 
        ->getCollection() 
        ->addIdFilter(array_rand(array_flip($parentCategory->getAllChildren(true)), 6)) 
        ->addAttributeToSelect('name') 
        ->addAttributeToSelect('thumbnail'); 
    ?> 
    <?php foreach ($children as $category): ?> 
    <li class="span3"> 
     <a href="<?php echo $category->getUrl(); ?>"> 
     <img alt="<?php echo $category->getName(); ?>" src="<?php echo $media; ?>catalog/category/<?php echo $category->getThumbnail(); ?>" /> 
     </a> 
    </li> 
    <?php endforeach; ?> 
</ul> 
+0

謝謝,正如我所需要的那樣工作 – user966834

相關問題