2

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

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

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

4

1 回答 1

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

于 2013-01-19T22:53:40.737 回答