webmastx
webmastx

Reputation: 683

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

Upvotes: 0

Views: 300

Answers (1)

Paulo Amaral
Paulo Amaral

Reputation: 863

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:

Upvotes: 0

Related Questions