如何访问json文件字段

时间:2017-11-06 08:17:51

标签: php json

{
 "took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
 },
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
  "doc_count_error_upper_bound" : 54,
  "sum_other_doc_count" : 1463,
  "buckets" : [
    {
      "key" : "ふるさと納税",
      "doc_count" : 30376
    }
   ]
 }
 }
}

这是json文件。我需要访问doc_count字段。

我试图像这样做

$trend_words = json_decode($file);
$aggregations = $trend_words->aggregations;
$buckets = $aggregations->{2}->buckets->{0};

但它不起作用。 有人可以帮忙。

4 个答案:

答案 0 :(得分:2)

$trend_words = json_decode($file,true);
$aggregations = $trend_words['aggregations']['2']['buckets'][0]['doc_count'];
print_r($aggregations)

你应该使用,否则你会得到一个stdclass对象,而不是你想要的数组。

答案 1 :(得分:1)

试试这个

<?php

$sJson = '
{
 "took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
 },
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
  "doc_count_error_upper_bound" : 54,
  "sum_other_doc_count" : 1463,
  "buckets" : [
    {
      "key" : "ふるさと納税",
      "doc_count" : 30376
    }
   ]
 }
 }
}
';

$aJson = json_decode($sJson, true);

echo $aJson['aggregations'][2]['buckets'][0]['doc_count'];

https://3v4l.org/kHfdo

答案 2 :(得分:1)

以下是答案:随着存储桶增加,您需要循环读取所有存储桶

$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'][2];
$buckets = array();
    foreach($aggregations as $element)
       $buckets[] = $element['buckets'];
    print_r($buckets);

答案 3 :(得分:0)

将Json设为数组并尝试

Visa