php-json操作,计数子节点,获取子节点


php json operation, count sub node, get sub nod

我有一些类似的json数据,现在我想统计所有节点"b",如果给它们一个数字,如何获得指定的节点。

[
   {
      "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);
        }
    }
} 

要计数,您必须保留一个计数器,如下所示:

$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 />';

根据您的代码,您可以使用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;
    $json = json_decode($txt); echo count($json, COUNT_RECURSIVE);