CakePHP:使用自定义数组提供paginate()

时间:2013-01-19 22:05:47

标签: cakephp pagination

我想用自己构建的数组提供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));
  }
}

我如何以最简单的方式做到这一点?

1 个答案:

答案 0 :(得分:2)

  1. 你有变量$ paginate和函数$ this-> paginate()的相同名称 - 你需要重命名一个。

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

  3. 您的小代码示例:

  4. 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);
    }
    

    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); }