vloryan vloryan - 3 months ago 9
PHP Question

same results for php if inside foreach

My problem is that as soon as my php variable was used for the first time, the same value shows up in every loop, though it is uncorrect:

$json_matches=file_get_contents('url');
$matches = json_decode($json_matches,true);

//json results
foreach($matches as $object)

//filter results
if ($object['season'] == $season && $object['localteam_id'] == $hteam) {

//add up localteam and visitorteam goals
$goals_match=$object['localteam_score']+$object['visitorteam_score'];

//check if result is larger than 4 and save value to variable
if($goals_match > 4) $goals_p4=1;

echo $object['id']." ". $goals_p4;

}


As soon as I have a correct result for
$goals_match > 4
the
1
shows up correctly. But in my next results no matter if wrong or right, the
1
appears again and again.

I have checked several posts in here, but have not found any tips to solve this problem. Would be great if you could help me here!

Thank you very much!

Answer

This is happening because you're not resetting or re-initialising the $goals_p4 variable once it has been used, as such it is keeping the value.

One way of fixing this would be the following, but you don't state what a default value for $goals_p4 should be, or if the value should be stored somewhere:

$json_matches=file_get_contents('url');
$matches = json_decode($json_matches,true);

//json results
foreach($matches as $object)
{
  //filter results
  if ($object['season'] == $season && $object['localteam_id'] == $hteam) 
  {
    $goals_p4 = ''; // reset to it is blank for each loop

    //add up localteam and visitorteam goals
    $goals_match=$object['localteam_score']+$object['visitorteam_score'];

    //check if result is larger than 4 and save value to variable
    if($goals_match > 4) 
    {
      $goals_p4=1; // will only be set to 1 if the $goals_match is over 4, if not it will remain default
    }

    echo $object['id']." ". $goals_p4;  // $goals_p4 will either be 1 or blank

  }    

}
Comments