php json操作,count子节点,get子节点

时间:2013-02-21 08:58:37

标签: php json

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

3 个答案:

答案 0 :(得分: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 />';

答案 1 :(得分: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;

答案 2 :(得分:0)

    $json = json_decode($txt); echo count($json, COUNT_RECURSIVE);