计算JSON对象

时间:2013-05-05 12:53:04

标签: php json

我有以下php代码从JSON格式化的Feed中返回一些值。

$json = file_get_contents("//URL HERE");
$data = json_decode($json, true);

foreach($data['users'] as $item)
{
  print $item['userName'];
  print ': ';
  print $item['status'];
  print ' - location: ';
  print $item['location']['y'];
  print ' / ';
  print $item['location']['x'];
  print '<br>';
}

此代码返回具有状态及其位置的用户的名称。 在用户结束时,我想计算它们。

Feed的格式如下:

{
 "startTime":"time",
 "users":
 [
 {
  "location": {
    "y": 47.61,
    "x": 21.52
  },
  "status": 48,
  "userName": "testuser",
},
{
  "location": {
    "y": 48.01,
    "x": 20.88
  },
  "status": 49,
  "userName": "testuser18",
}
],
  "startTime1": 1314,
  "endTime1": "141414"
}

我尝试使用以下代码:

$iCount = count($data);  //returns value 4
$iCount1 = count($item); //returns value 3
print $iCount;

但我需要计算有多少用户。基本上计算“用户”对象在Feed中出现的次数。

1 个答案:

答案 0 :(得分:2)

$json = file_get_contents("//URL HERE");
$data = json_decode($json, true);

echo count($data['users']);