How to sort Google Generated Keyword Ideas Result?
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
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:
Sort array of objects by object fields https://www.php.net/manual/en/function.iterator-to-array.phpThanks 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 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.
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.