0

Although, I have successfully implemented Google Keyword Planner API to generate Keyword Ideas in PHP with the link below.

https://developers.google.com/google-ads/api/docs/keyword-planning/generate-keyword-ideas

Does anyone know the fastest way to sort the result by AvgMonthlySearches?

// Iterate over the results and print its detail.
foreach ($response->iterateAllElements() as $result) {
    /** @var GenerateKeywordIdeaResult $result */
    // Note that the competition printed below is enum value.
    // For example, a value of 2 will be returned when the competition is 'LOW'.
    // A mapping of enum names to values can be found at KeywordPlanCompetitionLevel.php.
    printf(
        "Keyword idea text '%s' has %d average monthly searches and competition as %d.%s",
        $result->getText(),
        is_null($result->getKeywordIdeaMetrics()) ?
            0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearches(),
        is_null($result->getKeywordIdeaMetrics()) ?
            0 : $result->getKeywordIdeaMetrics()->getCompetition(),
        PHP_EOL
    );
}

Thanks

webmastx
  • 683
  • 1
  • 8
  • 30
  • For best performance, you should sort your results directly in the query. See the `ORDER BY` clause in https://developers.google.com/google-ads/api/docs/reporting/example#php – Paulo Amaral May 05 '21 at 11:20

1 Answers1

0

You could implement a function that can compare two instances of your object and use usort:

function cmp($a, $b) {
    return $a->getKeywordIdeaMetrics()->getAvgMonthlySearches() - $b->getKeywordIdeaMetrics()->getAvgMonthlySearches();
}

$list = iterator_to_array($response->->iterateAllElements());

usort($list, "cmp");

// $list will be your sorted array to work with from here onwards ... 

See more:

Paulo Amaral
  • 747
  • 1
  • 5
  • 24
  • Thanks for your prompt reply. I've placed you snipped before iteration like this: function cmp($a, $b) { return $a->getKeywordIdeaMetrics()->getAvgMonthlySearches() - $b->getKeywordIdeaMetrics()->getAvgMonthlySearches(); } usort($response, "cmp"); foreach ($response->iterateAllElements() as $result) { .... and I got a warning saying: Warning: usort() expects parameter 1 to be array, object given in /Applications/MAMP/htdocs As I expected the response variable from API was an array isn't it? Please help and thank you. – webmastx May 05 '21 at 06:54
  • 1
    @webmastx You should verify what the response is by dumping the variable. Then you'll see instance of which class it is and you can find documentation for it. – El_Vanja May 05 '21 at 08:19
  • You are dealing with an iterator and will need to convert to an array with `iterator_to_array` to be able to use `usort`. I updated the code of the answer if you want to try it. Be advised that this won't give you the best performance though. – Paulo Amaral May 05 '21 at 11:13