【问题标题】:CakePHP: feeding paginate() with a custom arrayCakePHP:使用自定义数组提供 paginate()
【发布时间】:2013-01-20 06:59:23
【问题描述】:

我想为 CakePHP 的 paginate() 函数提供一个我自己构建的数组,如下所示:

class SomeController extends AppController {

  var $paginate = array(
          'limit' => 25,
          'order' => array(
                  'Post.title' => 'asc'
          )
  );

  public function index(){

    $theArray = array(
      array(
        'Entity1'=>
          array('id'=>1, 'someField'=>'value1'),
        'SecondEntity'=>
          array('id'=>1, 'fieldTwo'=>'reallyInteresting')
      ),
      array(
        'Entity1'=>
          array('id'=>2, 'someField'=>'value2'),
        'SecondEntity'=>
          array('id'=>2, 'fieldTwo'=>'displayedValue')
      )
    );
    $this->set('data',$this->paginate($theArray));
  }
}

我该怎么做最简单的方法?

【问题讨论】:

    标签: cakephp pagination


    【解决方案1】:
    1. 变量 $paginate 和函数 $this->paginate() 的名称相同 - 您需要重命名一个。

    2. 不清楚您的订购字段 Post.title - 数据样本中没有这样的字段/表格。

    3. 给你的小代码示例:

    public function paginate($array, $page = 0) {
      // array_slice() to extract needed portion of data (page)
      // usort() to sort data using comparision function $this->sort()
      return(
        array_slice(
          usort(
            $array,
            array($this, 'sort') // callback to $this->sort()
          ),
          $page*$this->paginate['limit'],
          $this->paginate['limit']
        )
      );
    }
    
    public function sort($a, $b) {
      $result = 0;
      foreach($this->paginate['order'] as $key => $order) {
        list($table, $field) = explode('.', $key);
         if($a[$table][$field] == $b[$table][$field])
          continue;
         $result = ($a[$table][$field] < $b[$table][$field] ? -1 : 1) *
          ($order == 'asc' ? 1 : -1);
      }
      return($result);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      相关资源
      最近更新 更多