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 ?
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 = '';
}
}
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]];
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++;
}