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 ?

1
  • 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 excellent answer Commented Sep 9, 2016 at 13:19

3 Answers 3

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 = '';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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++;
}

Comments

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]];

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.