2012-11-19 38 views
1

我正在cakephp 2+项目中工作。我正在实施用于分类左右两个div组合中的产品列表的分页。我能够使左div,但不能正确的一个,因为抵消不能在分页设置。我需要在左边div中的半项和右边div中的半项,所以我可以设置限制但不能抵消。我怎样才能做到这一点?CakePHP分页与左右div组合

Controller code 

public function index() 
{ 

$rows=$this->Product->find('count', array('conditions'=>array('Product.allow'=>1))); 
if($rows%2==0) 
{ 
$this->paginate = array('conditions' => array('Product.allow'=>1,'limit'=>($rows/2)); 
$list_l = $this->paginate('Product'); 
$this->set('left_list',$list_l); 
$this->paginate = array('conditions' => array('Product.allow'=>1,'limit'=>($rows/2), 'offset'=>$rows/2)); 
$list_r = $this->paginate('Product'); 
$this->set('right_list',$list_r); 
} 
else 
{ 
$right_list=$this->Paginate('Product', array('Product.allow'=>1),array('limit'=>($rows-round($rows/2)), 'offset'=>round($rows/2))); 
} 
} 

View Code 

Foreach loop with array returned from controller 

回答

0

为什么不叫$this->paginate()一次遍历所有项目,并执行在查看自己的分裂?执行这两个调用相当浪费数据库资源。

在这种情况下,您可能需要在Controller中调用$ this-> paginate。假设你想在右左栏和五个五个项目:

$products = $this->paginate = array('conditions' => array('Product.allow'=>1, 'limit' => 10)); 
$this->set('products', $products); 

在视图:

<div class="left-column"> 
<?php 
    foreach ($products as $product) { 
    debug($product); 
    if ($count === 5) { 
     echo "</div>\n<div class=\"right-column\">"; 
     $count = 1; 
    } 
    $count++; 
    } 
?> 
</div> 

另一种方式是在控制器使用array_chunk。使用这个核心的PHP函数,你将得到多维数值索引数组,你可以循环并将子数组包装在相关的div中。

<?php 
    $limit = round(count($products)/2); 
    $products = array_chunk($products, $limit); 
    foreach ($products as $index=>$groupedProducts) { 
    echo ($index === 0) ? '<div class="left-column">': '<div class="right-column">'; 
    foreach ($groupedProducts as $product) { 
     debug($product); 
    } 
    echo '</div>'; 
    } 
?> 
+0

感谢mensch您的确切答复。我几乎完成了......将代码提供给将来的参考近.........再次感谢抱歉不能投票给你,因为我的repu却不允许这样做;) –