2013-02-21 39 views
1

我有一些这样的json数据,现在我想要统计所有的节点“b”,如果给他们编号,如何获得指定的节点。php json操作,计数子节点,得到子节点

[ 
    { 
     "a":[ 
     { 
      "b":"aaa" //in case this is the first node "b", definition number 1 
     }, 
     { 
      "b":"bbb" //this is the second node "b", definition number 2 
     } 
     ] 
    }, 
    { 
     "a":[ 
     { 
      "b":"ccc" //this is the third node "b", definition number 3 
     }, 
     { 
      "b":"ddd" //this is the forth node "b", definition number 4 
     } 
     ] 
    }, 
    { 
     "c":"eee" 
    }, 
] 

现在在这个例子中,有4个节点“b”,如何计算它们?以及如何在php代码中获得第三个节点“b”?

$json=json_decode($txt); 
foreach($json as $data){ 
    if($data->a){ 
     foreach($data->a as $row){ 
      echo $row->b.'<br />'; 
        //count($row->b); 
     } 
    } 
} 
+0

刚迭代之前添加一个计数var,并在循环内测试每个键的值。 – Imperative 2013-02-21 09:02:07

回答

1

算来,你必须保持一个计数器,这样的:

$counter = 0; 
$json = json_decode($txt); 
foreach ($json as $data) { 
    if ($data->a) { 
     foreach($data->a as $row){ 
      $counter++; 
      if ($counter == 3) { 
       echo 'Third "b": ' . $row->b . '<br />'; 
      } 
     } 
    } 
} 
echo 'Number of "b"s: ' . $counter . '<br />'; 
0

按照你的代码,你可以用isset运营商做到了:

$json=json_decode($txt); 
$count = 0; 
foreach($json as $data){ 
if($data->a){ 
    foreach($data->a as $row){ 
     if (isset($row->b)) 
      ++$count; 
     } 
    } 
} 
echo $count; 
0
$json = json_decode($txt); echo count($json, COUNT_RECURSIVE);