h0sfx0
h0sfx0

Reputation: 51

CakePHP: Custom pagination with an array

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?

Upvotes: 2

Views: 948

Answers (1)

Sumon Sarker
Sumon Sarker

Reputation: 2795

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.

Upvotes: 1

Related Questions