d33tah
d33tah

Reputation: 11561

CakePHP: feeding paginate() with a custom array

I'd like to feed CakePHP's paginate() function with an array I've built myself, like this:

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

How do I do it the easiest way?

Upvotes: 2

Views: 3259

Answers (1)

clover
clover

Reputation: 5170

  1. you have identical names of variable $paginate and function $this->paginate() - you need to rename one.

  2. it's not clear about your ordering field Post.title - there is no such field/table in the data sample.

  3. little code sample for you:

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

Upvotes: 2

Related Questions