2

I'm trying to learn json in php. Here's my json result from a ElasticSearch query.

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : null,
    "hits" : [ {
      "_index" : "xenforo",
      "_type" : "post",
      "_id" : "1816069",
      "_score" : null,
      "sort" : [ 1365037907 ]
    } ]
  }
}

I assume that my php code will look something like this:

$myData = json_decode($result);

foreach($myData->hits as $var) {
   $post_id[] = $var->_id;
}

Been looking for the answer for hours, I sure do appreciate any help. Thank you.

Edit: Here is the answer:

foreach($myData->hits->hits as $var) {
   $post_id[] = $var->_id;
}
6
  • 3
    What is your question? Commented Apr 13, 2013 at 20:44
  • See array.include-once.org on how to traverse data structures in PHP. Only ->hits->hits is meant to be iterated over. Commented Apr 13, 2013 at 20:47
  • yes please explain the question, what are you trying to accomplish with the JSON object? Commented Apr 13, 2013 at 20:50
  • I would like to populate the $post_id array with the _id in the json output. So in this case $post_id[0] should equal 1816069. Commented Apr 13, 2013 at 20:52
  • your current JSON object only shows one _id parameter but it seems what you are asking involves getting multiple _id so can you modify your JSON so that it shows how the structure will look with multiple _ids? Commented Apr 13, 2013 at 20:56

1 Answer 1

3

You're one ->hits short if you look at your JSON structure...

{
    "hits" : {
        "hits" : [ {
            "_id" : "1816069",

$myData = json_decode($result);

foreach($myData->hits->hits as $hit) {
    $post_id[] = $hit->_id;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.