I have just discovered you can get pagination results through the api by passing in the page parameter like so:
$projects = $client->get('projects/147/time-records?page=3')->getJson();
Is there a way of knowing how many time records a project has so I know how many times I need to paginate?
Alternatively, how would I go about retrieving several pages worth of data - i'm struggling with the code!
I have created an issue on Github - will await a response.
For now, I do the following:
// Get all the projects
// Set the page number
$page = 1;
// Create an empty array
$project_records = array();
// Get the first page of results
$project_records_results = $client->get('projects?page=' . $page)->getJson();
// Merge the results with base array
$project_records = array_merge($project_records, $project_records_results);
// Get the next page of results,
// if it returns something merge with the base array and continue
while ($project_records_results = $client->get('projects?page=' . ++$page)->getJson()) {
$project_records = array_merge($project_records, $project_records_results);
}
Sure. All paginated results will include following headers:
X-Angie-PaginationCurrentPage - indicates current page
X-Angie-PaginationItemsPerPage - indicates number of items per page
X-Angie-PaginationTotalItems - indicates number of items in the entire data set.
When you get header values, simple:
$total_pages = ceil($total_items_header_value / $items_per_page_header_value);
will give you number of pages that are in the collection.
Alternative: You can iterate through pages (by starting with page GET parameter set to 1, and incrementing it) until you get an empty result (page with no records). Page that returns no records is the last page.
Please note, that the headers are now all lowercase (v1)!
So the answer above should be corrected.
To get them call:
$headers = $client->get($path)->getHeaders();
Working code example from /api/v1/:
$paginationCurrentPage = isset($headers['x-angie-paginationcurrentpage'][0]) ? $headers['x-angie-paginationcurrentpage'][0] : NULL;
$paginationItemsPerPage = isset($headers['x-angie-paginationitemsperpage'][0]) ? $headers['x-angie-paginationitemsperpage'][0] : NULL;
$paginationTotalItems = isset($headers['x-angie-paginationtotalitems'][0]) ? $headers['x-angie-paginationtotalitems'][0] : NULL;
Related
Im making a big APi call, i have over 6000 records. Out of those 6000 i get 200 per page. So if we divide 6000 by 200 we get 30 pages in total.
So if I would want to get all records I'd need to make 30 different requests. I can speficy the amount per page in my request url parameters. Right now it looks like this:
$getRequest = $CallMonkeyApi->makeApiCall('GET','/address/get-all?apiKey=secret&page=1&size=200');
In the url you see a parameter "page=1" I would like this number to be dynamic from a loop that stops at 30. But I dont know where to start.
You can do this with a "for" loop
//An array for results
$getRequests = array();
//For every occurance where `x` is less than or equal to 30
for( $x = 1; $x<=30; $x++ ){
//Build the path to API call
$path = "/address/get-all?apiKey=secret&page=" . $x . "&size=200";
//Make API call and store the output on the $getRequests array of results
$getRequests[] = $CallMonkeyApi->makeApiCall('GET', $path);
}
Then you can access your $getRequests array by using $getRequests[$pageNumber]. So, for example, if I wanted to see page 5, i'd do print_r( $getRequests[4] ).
Note that the page number will be one less in the array because arrays start at 0.
I am creating a PHP class that use a 3rd party API. The API has a method with this request URL structure:
https://api.domain.com/path/sales?page=x
Where "x" is the page number.
Each page return 50 sales and I need to return an undefined number of pages for each user (depending on the user sales) and store some data from each sale.
I have already created some methods that get the data from the URL, decode and create a new array with the desired data, but only with the first page request.
Now I want to create a method that check if is there another page, and if there is, get it and make the check again
How can I check if there is another page? And how to create a loop that get another page if there is one?
I have already this code, but it create an infinite loop.
require('classes/class.example_api.php');
$my_class = new Example_API;
$page = 1;
$sales_url = $my_class->sales_url( $page );
$url = $my_class->get_data($sales_url);
while ( !empty($url) ) {
$page++;
$sales_url = $my_class->sales_url( $page );
$url = $my_class->get_data($sales_url);
}
I don't use CURL, I use file_get_content. When I request a page out of range, I get this result:
string(2) "[]"
And this other after json_decode:
array(0) { }
From your input, in the while loop, you change the $url (which actually holds the data return by the API call) and this is checked for emptiness, if I'm correct.
$url = $my_class->get_data($sales_url);
If the above is just the original response (so in case of page out of range a string "[]"), it will never get empty("[]") to true. So my guess is that the return value from get_data is this string, while it should be the actual array/json even if the result is empty (ie I suspect that you perform the json_decode once you have collected the data e.g. outside the loop).
If this is the case, my suggestion would be to either check for "[]" in the loop (e.g. while ($url !== "[]")) or within the loop decode the response data ($url = json_decode($url)).
From my experience with several API's, the response returns the number of rows found, and x number per page starting with page 1.
In your case, if the response has the number of rows then just divide it by the x number page and loop through the results as page numbers.
$results = 1000;
$perPage = 50;
$pages = ceil($results/$perPage);
for (i=1; $i <= $pages; $i++){
// execute your api call and store the results
}
Hope this help.
From the responses you've shown, you get an empty array if there are no results. In that case, you could use the empty method in a loop to determine if there's anything to report:
// Craft the initial request URL
$page = 1;
$url = 'https://api.domain.com/path/sales?page=' . $page;
// Now start looping
while (!empty(file_get_contents($url)) {
// There's data here, do something with it
// And set the new URL for the next page
$url = 'https://api.domain.com/path/sales?page=' . ++$page;
}
That way it will keep looping over all the pages, until there is no more data.
Check http response headers for total number of items in set
there. I'm having a problem with creating arrays in certain conditions in php, i'll try to explain. Here's my code:
for ($i = 1; $i < $tamanho_array_afundamento; $i++) {
if ($array_afundamento[$i] - $array_afundamento[$i - 1] > 1) {
$a = $array_afundamento[$i - 1];
$con->query('CREATE TABLE IF NOT EXISTS afunda_$a
SELECT (L1_forma_tensao_max + L1_forma_tensao_min)/2 as L1_forma_tensao, (L2_forma_tensao_max + L2_forma_tensao_min)/2 as L2_forma_tensao, (L3_forma_tensao_max + L3_forma_tensao_min)/2 as L3_forma_tensao
FROM afundamento
WHERE id > $prevNum AND id < $a');
$tabelas_intervalos_afunda1 = ($con->query("SELECT * FROM afunda_$a");
while ($row = $tabelas_intervalos_afunda->fetch(PDO::FETCH_ASSOC)) {
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
$prevNum = $a;
}
}
So as u can see, i have an if statement in a for loop, what i'm wishing to do is to create
one set of:
{
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
every time the if statement is runned. I was trying replacing this in the original code:
{
$array_forma_onda_fase1_afund_$a[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_$a[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_$a[] = $row['L3_forma_tensao'];
}
so as $a is changed everytime the if statement is accessed, i could have a different set of these arrays for everytime the if statement is accessed, but php doesn't accept this and i wouldn't have a very good result, though if i can reach it i would be pleased.
But my goal is to get:
{
$array_forma_onda_fase1_afund_1[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_1[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_1[] = $row['L3_forma_tensao'];
}
{
$array_forma_onda_fase1_afund_2[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_2[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_2[] = $row['L3_forma_tensao'];
}
...
where the last number represents the array retrieved for the n-th time the if statement runned. Does someone have a tip for it?
Thanks in advance! Would appreciate any help.
EDIT
As asked, my real world terms is as follows:
I have a table from which i need to take all the data that is inside a given interval. BUT, there's a problem, my data is a sine function whose amplitude may change indefinite times (the data bank is entered by the user) and, when the amplitude goes inside that interval, i need to make some operations like getting the least value achieved while the data was inside that interval and some other parameters, for each interval separately, (That's why i created all those tables.) and count how many times it happpened.
So, in order to make one of the operations, i need an array with the data for each time the databank entered by the user goes in that interval (given by the limits of the create query.).
If i were not clear, just tell me please!
EDIT 2
Here's the image of part of the table i'm working with:
http://postimg.org/image/5vegnk043/
so, when the sine gets inside the interval i need, it can be seen by the L1_RMS column, who accuses it, so it's when i need to get the interval data until it gets outside the interval. But it may happens as many times as this table entered by the user brings it on and we need to bear in mind that i need all the intervals separately to deal with the data of each one.
Physics uh?
You can do what you wanted with the arrays, it's not pretty, but it's possible.
You can dynamically name your arrays with the _$a in the end, Variables variables, such as:
${"array_forma_onda_fase3_afund_" . $a}[] = "fisica é medo";
I have this function in order to retrieve the count of Facebook comments to blog posts:
function comment_count($url) {
$json = json_decode(file_get_contents('https://graph.facebook.com/?ids=' . $url));
return ($json->$url->comments) ? $json->$url->comments : 0;
}
However if I insert it in a loop fetching the results of a query in order to retrieve five posts on a page, this function is seriously affecting the speed of the website (the page takes up to 6-7 seconds to load).
Is there a way to avoid this? Why is it so slow?
Thanks
Pass in a comma separated list of URLs to the ids parameter to get all the counts at once, or alternatively, cache them on the server side and use those values.
Example: https://graph.facebook.com/?ids=http://www.google.com,http://www.bing.com,http://www.yahoo.com
This is specified in Facebook's Graph API Reference under the section "selection"
An example implementation follows:
<?php
function comment_count($urls) {
$json = json_decode(file_get_contents('https://graph.facebook.com/?ids=' . implode(',', array_map("rawurlencode", $urls))));
$output = Array();
foreach($json as $url=>$data)
{
$output[$url] = isset($data->comments) ? $data->comments : 0;
}
return $output;
}
var_dump(comment_count(Array('http://www.facebook.com/', 'http://www.google.com')));
I hope this helps!
Let me explain my issue in detail
I have a table called products
Products : Name , views , sale_wanted , added_date
I am listing all my products in a view .
I am handling sale wanted through a flag means 0 or 1.
There are some links to sort the listing.
Most Viewed
Wanted
For Sale
New Arrivals
Now when user clicks all the listing is sorted according to the parameter i am sendig.
I want to use pagination class of Codeigniter.
Here comes some issues.
When i am clicking let suppose Wanted and sending a parameter it lists all the products wanted.
Now i click on a pagination link and the wanted parameter is gone
and the list becomes without wanted parameter.
Same goes with the other Anchors.
I have to restrict it so it still has my parameter.
The second problem is that what i see Codeigniter is laking.
I need some links that user can select. Means i want to give the user functionality to select how many products he wants to see in one page.
Let suppose 5 ,10 ,15 ,20
Choosing the greater number will reduce the number of pages.
And still i want the same functionality.
The important point is that i want to handle all this just in one shot means i dont want to duplicate my code for every anchor.
I need suggestions from expert and any help regarding Pagination library.
$seg=3
$noOfresultsToshow=$this->uri->segment('5')//use if else for by default no of results
$typeOfresult=$this->uri->segment('4'); //Most Viewed Wanted For Sale New Arrivals
$config['total_rows'] = $countqueryresults;// mention the total rows here
$config['per_page'] = $noOfresultsToshow;
$config['uri_segment'] = $seg;
$this->pagination->initialize($config);
$data['yourvariable'] = $this->model_name->getData($config['per_page'], $this->uri->segment($seg),$typeOfresult);
$data['links'] = $this->pagination->create_links();
in your view file echo $links;
I have found a solution for the issue.
I have made two methods in Codeigniter Pagination library
Here they are
Defined two new variables
var $base_link = '';
var $per_page_link = TRUE;
var $per_page_array = array();
The user can define both of them while initializing
$config['per_page_link'] = TRUE;
$config['per_page_array'] = array(5,10,15,20);
$this->pagination->initialize($config);
Now the methods
public function create_per_page()
{
$CI =& get_instance();
$output = '';
$current = $CI->uri->segment(3,5);
if($this->per_page_link === TRUE AND count($this->per_page_array) > 1){
foreach($this->per_page_array as $row){
if($current == $row){
$output .= $this->cur_tag_open . $row . $this->cur_tag_close;
$output .= ' ';
}else{
$output .= ''.$row.'';
$output .= ' ';
}
}
}
return $output;
}
And the other is create_per_page_links(). I have just copied the code of create_links method in it and modified it. In the start of create_per_page_links() i have added these extra lines.
$this->per_page = $CI->uri->segment(3,5);
$this->uri_segment = $CI->uri->segment(4,1);
However, This will only work with segments on. i haven't tested it with query string. Also if per_page_link is FALSE both methods will not work.
Calling create_per_page_links will generate the following
« First < 1 2 3 4 5 > Last »
And create_per_page will generate the following
5 10 15 20
And Done