2013-02-21 77 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);