dongwu9170 2017-09-11 07:08
浏览 94
已采纳

正确格式化foreach和if语句

I'm trying to figure out what I'm doing wrong here, or if this is even formatted improperly all together. I am getting an error on line 3.

foreach($pge['feats'] as $val) {
} if ($val['name'] == 'wins' && $val['value'] == '1')
    foreach ($val['value'] == '1' as $count) {
        echo count($count);
}

Here's another way I tried...

foreach($pge['feats'] as $val)
 if ($val['name'] == 'wins' && $val['value'] == '1')
    foreach ($val['value'] == '1' as $count) {
        echo count($count);
}

Here's some of the json i'm using. I have several files that will look like this with different values for the wins/value object. My statement will go through each one and check for the wins value to be "1", and then add up the total "1" values together..

Partial contents of my $pge json

{
  "playerCount": "2",
  "remote": "0",
  "feats": [
    {
      "name": "score",
      "value": "32"
    },
    {
      "name": "wins",
      "value": "0"
    }
  ]
}

Thank you!

  • 写回答

1条回答 默认 最新

  • duankang5882 2017-09-11 07:12
    关注
    <?php
    
    function game_won(array $game) {
      $win = false;
      foreach($game['feats'] as $val) {
        if ($val['name'] == 'wins' && $val['value'] == '1') {
          $win = true;
        }
      }
      return $win;
    }
    
    function sum_game_wins(array $games) {
      $sum = 0;
      foreach($games as $game) {
        if(game_won($game)) {
          $sum++;
        }
      }
      return $sum; 
    }
    
    $game_1 =<<<JSON
    {
      "playerCount": "2",
      "remote": "0",
      "feats": [
        {
          "name": "score",
          "value": "32"
        },
        {
          "name": "wins",
          "value": "1"
        }
      ]
    }
    JSON;
    
    $game_2 =<<<JSON
    {
      "playerCount": "2",
      "remote": "0",
      "feats": [
        {
          "name": "score",
          "value": "32"
        },
        {
          "name": "wins",
          "value": "0"
        }
      ]
    }
    JSON;
    
    $game_1 = json_decode($game_1, TRUE);
    $game_2 = json_decode($game_2, TRUE);
    
    var_dump(sum_game_wins(array($game_1, $game_2)));
    

    Output:

    int(1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?