2

I am trying to paginate an array in CakePHP. The array is extracted from a JSON file, thus not using any database queries or whatsoever. I'm trying to stick to the functions of CakePHP to make sure I don't write useless code. I have been looking around and can not find any answer on my question.

The array is as of the following:

array(161) { 
    [0]=> array(8) { 
        ["id"]=> int(589) 
        ["status"]=> string(7) "running" 
        ["threads"]=> int(12) 
        ["create_time"]=> float(1487712882.42) 
        ["memory_usage_precent"]=> float(11.0328674316)             
        ["cpu_usage_precent"]=> int(62) 
        ["cwd"]=> string(1) "/"   
        ["process_name"]=> string(16) "plugin-container" 
    }
}

This is one row of the 161 rows in the array. How can I paginate this by using CakePHP's methods?

1
  • 1
    Cake's Paginator Component and Paginator Helper are specifically designed to Paginate Models, loaded from Table classes, by manipulating the Query underneath. They can't be used to paginate an array. You need to paginate this manually. Commented Mar 17, 2017 at 14:14

1 Answer 1

1

Here is an example for making pagination from Array

Step 1 - PHP Data Array :

$data = [
  [
    "id"=> 0,
    "status"=> "running"
  ],[
    "id"=> 1,
    "status"=> "running"
  ],
  #More Arrays ...
];

Step 2 - Prepare Data [Calculations]

$TotalDatas     = count($data); #Total number of Data in Array
$StartFrom      = 0; #Start from Array index
$DisplayLimit   = 2; #Limit the result per page
$CurrentPage    = isset($_GET['page'])? $_GET['page'] : 0; #Get the page number value from URL

$StartFrom      = $CurrentPage*$DisplayLimit; #Update the Array index by calculating Page number and Limit

Step 3 - Display Data using loop :

for($i=$StartFrom; $i<$StartFrom+$DisplayLimit; $i++){ #Increase the Array index by Limit
  if($i>=$TotalDatas){
    continue; #Break Or put some message, Because no more Data in Array
  }
  var_dump($data[$i]);
}

Browse URL like as - localhost?page={PAGE_MUNBER_HERE}

Example :

localhost?page=3

Note : Above codes is the simple example of basic pagination.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.