I have a php array which I got as a response from a server so I can't change it,
print_r($array);
// result is below
array(
'responseHeader'=>array(
'status'=>0,
'QTime'=>0,
'params'=>array(
'indent'=>'true',
'q'=>'rajnikanth',
'_'=>'1383362349068',
'wt'=>'php')),
'response'=>array('numFound'=>2,'start'=>0,'docs'=>array(
array(
'id'=>'31546690',
'title'=>'Jayan quotes',
'_version_'=>1450551735544184832),
array(
'id'=>'597727',
'title'=>'List of Internet phenomena',
'_version_'=>1450551735290429440))
))
How to access each of the title values in this array? I tried to use $array[0] but it erred out saying no offset set.
foreach ($array['response']['docs'] as $doc) {
echo $doc['title'];
}
$array appears to be an array of two keys, responseHeader and response. The response key contains a docs key, which is an array of arrays. Each of these arrays appears to have a title.
That's because this is not an indexed array... it's an associative one. Meaning that the contents are referenced by a string key instead of a number.
The PHP construct for this is:
foreach ($array as $key => $value) {
}
In your case, this loop would iterate twice.
The first iteration:
$key --> "responseHeader"
$value --> an array containing the keys "status", "QTime", and "params"
The second iteration:
$key --> "response"
$value --> an array containing the keys "numFound", "start", and "docs"
Note that the values found under both "params" and "docs" are also associative arrays. So feel free to nest loops inside the first one you did.
Usually though, you'll know beforehand the keys in an associative array, so you can access it using $array['some_key']
. If you don't, then one of PHP's built-in array functions may come in handy (array_key_exists()
, etc.).