正确格式化foreach和if语句

时间:2017-09-11 07:08:19

标签: php json for-loop if-statement foreach

我正在试图找出我在这里做错了什么,或者如果这甚至是不正确的格式化的话。我在第3行收到错误。

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

这是我尝试的另一种方式......

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

这是我正在使用的一些json。我有几个文件看起来像这样,具有wins / value对象的不同值。我的陈述将遍历每一个并检查胜利值是否为“1”,然后将总“1”值加在一起..

我的$ pge json的部分内容

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

谢谢!

1 个答案:

答案 0 :(得分:1)

<?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)));

输出:

int(1)