2013-01-19 53 views
2

我想用一個數組我已經建立了自己養活CakePHP的paginate()功能,像這樣: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)); 
    } 
} 

我怎麼做最簡單的方法?

回答

2
  1. 你有變量$ 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); 
}