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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程