0

I have the following JSON response example (usually a long response):

  "responseHeader":{
  "status":0,
  "QTime":2,
  "params":{
  "indent":"true",
  "start":"0",
  "q":"hi",
  "wt":"json",
  "rows":"2"}},
"response":{"numFound":69,"start":0,"docs":[
  {
    "id":335,
    "Page":127,
    "dartext":" John Said hi !      ",
    "Part":1},
  {
    "id":17124,
    "Page":127,
    "Tartext":" Mark said hi ",
    "Part":10}]
}}

I only want to access the property with the type of string the problem is the property's name is not constant so I can't use something like :

$obj =json_decode(file_get_contents($data));
$count = $obj->response->numFound;

for($i=0; $i<count($obj->response->docs); $i++){
   echo $obj->response->docs[$i]->dartext;
} 

because in the other object it's not dartext it's Tartext.

how can I access the third property by it's index not it's name ?

MRK
  • 37
  • 7
  • It's important that you first figure out where the key resides. Even if it exists (using the below answers you can figure that out) - there is no guarantee the objects keys will always be in the same order... See [this](http://stackoverflow.com/a/5525820/3249501) excellent answer – GrayedFox Sep 09 '16 at 13:19

3 Answers3

1

You can try this one:

$my_key = array();
$obj =json_decode(file_get_contents($data));
$count = $obj->response->numFound;
$k =1;
foreach ($obj->response->docs as $k => $v) {
    if ($k == 3) {
        $my_key[$k] = $v; // Here you can put your key in 
    }
    $k++;
}
Nipun Tyagi
  • 853
  • 8
  • 26
1

Better way is to check if key exists, because order of results can be changed

<?php
$response = $obj->response;
foreach($response->docs as $doc) {
    if (isset($doc->dartext)) {
        $text = $doc->dartext;
    } elseif (isset($doc->Tartext)) {
        $text = $doc->Tartext;
    } else {
        $text = '';
    }
}
cetver
  • 7,930
  • 5
  • 31
  • 50
0

From the docs:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

If you use json_decode(file_get_contents($data), true) it will return an array.

After that, you can do something like this to access the array by the index not the key.

$keys = array_keys($json);
echo $json[$keys[2]];
silentw
  • 4,479
  • 4
  • 22
  • 44