php json操作,计数子节点,获取子节点
我有一些类似这样的json数据,现在我想计算所有节点“b”,如果给它们编号,如何获得指定的节点php json操作,计数子节点,获取子节点,php,json,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 numbe
[
{
"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);
}
}
}
$json=json\u解码($txt);
foreach($json作为$data){
如果($data->a){
foreach($data->a as$行){
echo$row->b.“
”;
//计数($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 />';
$counter=0;
$json=json_解码($txt);
foreach($json作为$data){
如果($data->a){
foreach($data->a as$行){
$counter++;
如果($counter==3){
回显“第三个“b”:“$row->b.”
;
}
}
}
}
回显“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 />';
$counter=0;
$json=json_解码($txt);
foreach($json作为$data){
如果($data->a){
foreach($data->a as$行){
$counter++;
如果($counter==3){
回显“第三个“b”:“$row->b.”
;
}
}
}
}
回显“b”的编号:”$柜台。”
;
按照您的代码,您可以使用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;
按照您的代码,您可以使用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;
只需在迭代之前添加一个count变量,并在循环内测试每个键的值。只需在迭代之前添加一个count变量,并在循环内测试每个键的值。