Search code examples
phparraysgoogle-analytics-api

How to force an array to display all the values?


the output for my array look similar to this after print_r($segments):

Array
(
    [kind] => analytics#segments
    [username] => [email protected]
    [totalResults] => 2334
    [startIndex] => 1
    [itemsPerPage] => 1000
    [items] => Array
    (
        [0] => Array
            (
                [id] => -1
                [kind] => analytics#segment
                [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-1
                [segmentId] => gaid::-1
                [name] => All Visits
                [definition] => 
            )
...

        [999] => Array
            (
                [id] => -1
                [kind] => analytics#segment
                [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-1
                [segmentId] => gaid::-1
                [name] => All Visits
                [definition] => 
            )
    )
)

This array is an output from google analytics API PHP, the max that it displayed me is 1000 rows as mentioned in the itemsPerPage parameter, but I do have more than 1000, close to 2334 as mentioned in totalResults parameter.

Does some one have any idea how to force it to display all output at once?

When I run this :

 $nextLink = $results->getNextLink()
            ? $results->getNextLink() : 'none';

print($nextLink);

The output is a link: https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?start-index=1001&max-results=1000

Accoring to this documentation I have to use the parameter called max-results to display more results per page, but I have no idea how to do so, no much documentation about it.

Any idea how to get the rest of the results using the max-results parameter or the link?


Solution

  • Quick Answer: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working

    Look at the Pagination Information, it seems like your data should have a getNextLink() and getPreviousLink() which may not be part of the data and would not print in a print_r().

    When accessing an API through network, and not knowing how much information the API needs to return, you don't want to risk sending larges amount of data all at once. This could cause a lot of unnecessary traffic and slow the entire system down.

    One solution, Pagination, is to send back a set number of responses (1000 in this case) and if the user of the API needs more, have them request the next set explicitly.

    Psuedo Code: (Sorry I don't have a working Google-API setup to try this on)

    $finalArray = array();
    
    //Copy $segments into $finalArray;
    while(!empty($segments->getNextLink()))
    {
        //Use $segments->getNextLink()
        //$segments now contains the next set of data
        //Copy $segments into $finalArray;
    }