I want to filter information inside the foreach and to return as result only some of them.

This is the code :

    $keywords = "";     $avgmonthly = "";     $compet ="";     foreach ($response->getResults() as $result) {         $avgmonthly = $result->getKeywordIdeaMetrics()->getAvgMonthlySearches()->getValue();         $compet = $result->getKeywordIdeaMetrics()->getCompetition();         $log = $this->getLogger();         $log->err($response->serializeToJsonString());         if ($avgmonthlysearch > 10 && $competition== 4) {             $keywords .= $result->getText()->getValue() . ",";         }     }         return $keywords; 

in my log i see this results:

{"results":[{"text":"world","keywordIdeaMetrics":  {"avgMonthlySearches":"140","competition":"HIGH"}},  {"text":"today ","keywordIdeaMetrics":{"avgMonthlySearches":"10","competition":"HIGH"{"text":"office","keywordIdeaMetrics":{"avgMonthlySearches":"5","competition":"LOW"}} 

when i try to call this function i get this error : Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function getAvgMonthlySearches() on null

Tag:google-ads-api, php

Only one comment.

  1. Melvyn Marigny

    If your goal is just to espace this case, you can add an if condition ( As $result->getKeywordIdeaMetrics() can be null, it will not go inside this if condition )

    foreach ($response->getResults() as $result) { if ($result->getKeywordIdeaMetrics()) { $avgmonthly = $result->getKeywordIdeaMetrics()->getAvgMonthlySearches()->getValue(); $compet = $result->getKeywordIdeaMetrics()->getCompetition(); } $log = $this->getLogger(); $log->err($response->serializeToJsonString()); if ($avgmonthlysearch > 10 && $competition== 4) { $keywords .= $result->getText()->getValue() . ","; } }

Add a new comment.