0
{
 "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
    }
   ]
 }
 }
}

This is the json file . I need to access the doc_count field.

I am trying to do it like this

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

But its not working. Can someone help.

Kunal Kakade
  • 107
  • 2
  • 10
  • The answers should work. A direct approach would be `$buckets = $aggregations->{2}->buckets[0];`. Curly brackets {} in json will be php objects (unless switched off), and you need `->`. Square brackets [] will be php arrays and you need `[]`. – jh1711 Nov 06 '17 at 08:28

4 Answers4

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

You should use ,true otherwise you will get an stdclass object and not an array you want.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
1

try this

<?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

Mark
  • 780
  • 1
  • 6
  • 17
1

Here is the answer, As the buckets increases you need to have a loop through to read all the buckets

$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'][2];
$buckets = array();
    foreach($aggregations as $element)
       $buckets[] = $element['buckets'];
    print_r($buckets);
Jinna Balu
  • 6,747
  • 38
  • 47
0

Make Json to array and try

$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'];
$buckets =$aggregations[2]['buckets'][0];
Arafath
  • 1,090
  • 3
  • 14
  • 28