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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘