2010-11-14 97 views
1

我正在使用JSON数据的第一次,我有一些PHP抓住一些像下面的JSON数据(除了有几百测量身体)。使用PHP的foreach从JSON数据创建数组的数组

$json = file_get_contents("http://wbsapi.withings.net/measure?action=getmeasures"); 
$json_o = json_decode($json); 

如何使用的foreach,比方说,创建用于type = 1值的一维数组?

{ 
     "status": 0, 
     "body": { 
      "updatetime": 1249409679, 
      "measuregrps": [ 
       { 
        "grpid": 2909, 
        "attrib": 0, 
        "date": 1222930968, 
        "category": 1, 
        "measures": [ 
         { 
          "value": 79300, 
          "type": 1, 
          "unit": -3 
         }, 
         { 
          "value": 652, 
          "type": 5, 
          "unit": -1 
         }, 
         { 
          "value": 178, 
          "type": 6, 
          "unit": -1 
         }, 
         { 
          "value": 14125, 
          "type": 8, 
          "unit": -3 
         } 
        ] 
       }, 
       { 
        "grpid": 2908, 
        "attrib": 0, 
        "date": 1222930968, 
        "category": 1, 
        "measures": [ 
         { 
          "value": 78010, 
          "type": 1, 
          "unit": -3 
         } 
        ] 
       }, 
       { 
        "grpid": 2907, 
        "attrib": 0, 
        "date": 1222930968, 
        "category": 1, 
        "measures": [ 
         { 
          "value": 77300, 
          "type": 1, 
          "unit": -3 
         }, 
         { 
          "value": 678, 
          "type": 5, 
          "unit": -1 
         } 

        ] 
       }, 


      ] 
     } 
    } 
+0

有时一个人的目标是更清楚,询问比人阅读的人。输出是什么呢? 'array(/ * ... * /)'符号会特别有用。 – Matchu 2010-11-14 20:01:20

回答

0

喜欢的东西

$values = array(); 

foreach($json_o->body->measuregrps as $group){ 
    foreach($group->measures as $measure){ 
    if($measure->type == 1){ 
     $values[] = $measure->value; 
    } 
    } 
} 

print_r($values); 

会做

2
$json_o = json_decode($json,true); 

$result = array(); 

foreach ($json_o['body']['measuregrps'] as $measuregrp) 
foreach ($measuregrp['measures'] as $measure) 
    if ($measure['type'] == 1) 
    $result []= $measure['value']; 
+1

但下次请尝试自己提出一些代码,那么如果它不起作用,我们可以提供帮助。 – AndreKR 2010-11-14 20:03:59

+0

这实际上是行不通的,因为'body'等等都是stdClass的实例。它们不是数组,因此它们不能被称为数组。 – Harmen 2010-11-14 20:10:03

+2

它确实有效,因为第二个参数表示结果应该使用关联数组而不是标准对象。 http://php.net/manual/en/function.json-decode.php – PatrikAkerstrand 2010-11-14 20:17:05