1

我有一些这样的 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);
        }
    }
} 
4

3 回答 3

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 />';
于 2013-02-21T09:04:17.123 回答
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;
于 2013-02-21T09:08:14.197 回答
0
    $json = json_decode($txt); echo count($json, COUNT_RECURSIVE); 
于 2013-02-21T09:37:24.630 回答