Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jponsen's avatar

Google Analytics API group visitors by month

Hi,

The question below is not really a Laravel related question, however it is used in Laravel. I can't it to work, and some of you guys might know why.

I'm currently creating a dashboard for displaying and combing data sources. And I'm struggling with reformatting the data retrieved from one of the calls.

I'm querying visitors/user statistics using the following code:

        $request = $this->analytics->data_ga->get( 'ga:' . $view, '365daysAgo', 'yesterday', 'ga:users,ga:sessions', [
            'dimensions' => 'ga:date',
        ] );

        $data = [];

        foreach ( $request->rows as $row ) {
            $date = substr( $row[0], 0, 6 );

            if ( ! isset( $data[ $date ] ) ) {
                $data[ $date ]['visitors'] = 0;
                $data[ $date ]['sessions'] = 0;
            }

            $data[ $date ]['visitors'] += intval( $row[1] );
            $data[ $date ]['sessions'] += intval( $row[2] );
        }

        return $data;

But when I loop through the received data, count it, the output is different from Google Analytics itself.

Example output (november 2018):

        "201811": {
            "visitors": 80496,
            "sessions": 97401
        },

The result of vistors should be around ~ 55 K, but the amount of sessions seems correct. Google Analytics itself also shows around 55 K.

I've tried multiple ways, one of them is changing the date key specified by Google to a date object, and collecting using a d-Y format, another one is using strlen for extracting the first 6 characters (output: YYYYMM) - Both ways give the same result, which is not correct.

I also tried using another dimensions like ga:month - It returns the correct results, except for the current month. It looks like the results for the current month are just made up.

Does anyone have an idea how to get correct results grouped by month for the past year?

Thanks in advance!

0 likes
0 replies

Please or to participate in this conversation.