如果在foreach内,php的结果相同

时间:2016-08-23 12:41:59

标签: php

我的问题是,只要我的php变量第一次被使用,每个循环中都会显示相同的值,尽管它不正确:

$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;

    }    

只要$goals_match > 4得到正确的结果,1就会正确显示。但是在我的下一个结果中,无论是错还是错,1都会一次又一次出现。

我在这里查了几篇帖子,但没有找到解决这个问题的任何提示。如果你能在这里帮助我会很棒!

非常感谢!

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为一旦使用了$goals_p4变量,你就不会重置或重新初始化它,因为它保留了这个值。

解决此问题的一种方法如下,但您没有说明$ goals_p4的默认值应该是什么,或者该值是否应存储在某处:

$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

  }    

}