8

I started using Google Analytics 4 Data API and downloaded the PHP library to create the requests. I have been playing a little and my request is working good so far, but when I need to sort it I don't know exactly how to pass that data, I have been trying many ways but no luck.

Check "orderBys" data, there I supposed to pass orderType and dimensionName to filter by dimensions date so it should be something like "ordertype" => ALPHANUMERIC and "dimensionName => "date"

Any tip would be much appreciated :)

$response = $client->runReport([
          'property' => 'properties/' . $property_id,
          'dateRanges' => [
              new DateRange([
                  'start_date' => '7daysAgo',
                  'end_date' => 'yesterday',
              ]),
          ],
          'dimensions' => [new Dimension(
              ['name' => 'day']
          ),
          ],
          'metrics' => [

            new Metric(['name' => 'newUsers']),

            new Metric(['name' => 'active7DayUsers']),
          
          ],

          'orderBys' => [],
      ]);
Daniel Soublett
  • 849
  • 2
  • 8
  • 23

1 Answers1

13

This works for me:

Note that is used the V1beta package

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;


$response = $client->runReport([

    // ...

    'orderBys' => [
        new OrderBy([
            'dimension' => new OrderBy\DimensionOrderBy([
                'dimension_name' => 'month', // your dimension here
                'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
            ]),
            'desc' => false,
        ]),
    ],
]);

I had similar struggle, the documentation is really bad.

btx
  • 1,972
  • 3
  • 24
  • 36
  • Thanks a lot for this. it worked perfectly, how did you find out about it? would be nice to read more about that. – Daniel Soublett Nov 20 '21 at 00:52
  • 6
    @Daniel 2 hours of reading through the package source, the data api doc and a lot trial and error – btx Nov 21 '21 at 13:08
  • 5
    I hope it's OK to leave this comment here, even though it doesn't directly relate to the question. I've spent hours trying to solve this in Python and kept ending up back here. I eventually worked out the syntax, so just wanted to share it in case anyone else takes the same route as me: `order_bys = [OrderBy(dimension = OrderBy.DimensionOrderBy(dimension_name = "date"))]` and make sure to import OrderBy - Thanks anyway @btx your answer helped a lot! – Dave Jul 19 '22 at 16:11
  • 1
    It worked thanks. I just had to import the namespace - use Google\Analytics\Data\V1beta\OrderBy; – Dharmesh Jan 20 '23 at 11:49