1

我在一个 cakephp 2+ 项目中工作。我正在实现分页以在两个左右 div 组合中对产品列表进行排序。我可以制作左 div 但无法制作右 div,因为无法在分页中设置偏移量。我需要左 div 中的一半项目和右 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
4

1 回答 1

0

为什么不调用$this->paginate()一次并遍历所有项目并在视图本身中执行拆分?执行这两个调用相当浪费数据库资源。

在这种情况下,您将在控制器中调用 $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>

Another way would be to use array_chunk in the Controller. Using this core PHP function you'll end up with multidimensional numerically indexed array which you can loop over and wrap the child arrays in their relevant divs.

<?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>';
  }
?>
于 2012-11-20T09:26:53.947 回答