Reputation: 2444
I have made a http request to my api using Guzzle library as follow :
$client = new Client();
$response = $client->request(
'GET',
config('some_url');
$serverResponse = json_decode($response->getBody(),true);
if ($serverResponse['result']) {
$data = $serverResponse['data'];
Now I got the response as
{
"result": true,
"data": {
"101": {
"id": 101,
"name": "ABCD",
"age" : 24
},
"102": {
"id": 102,
"name": "EFGH",
"age" : 24
},
"103": {
"id": 103,
"name": "IJKL",
"age" : 24
},
}
}
The problem is I need to read and push the object models 101,102,103 to a separate array. for this I try to get the objects as following options. but I could not able to get the results rather than errors.
$obj = $data[0];
It returns Undefined offset: 0 error
Upvotes: 1
Views: 978
Reputation: 11
If you simply want to re-index the array so that the keys are [0]
, [1]
, [2]
, etc. you can use the following:
$newArray = array_values($data);
You will then be able to access the first sub-array with $newArray[0]
, the second with $newArray[1]
, etc.
Upvotes: 1
Reputation: 680
Because your data is being manually indexed, as opposed to something like:
{
"data": {
0: {
"id": 101,
...
},
1: {
"id": 102,
...
},
...
}
}
You will need to specify these indexes when fetching the data. E.g:
$data["101"]
To do this for dynamically set data you can use array_keys
$obj = $data[array_keys($data)[0]];
Using array_keys
allows you to search $data
by the numerical index of $data
Upvotes: 2
Reputation: 80
You can convert the response to object and then you can access the properties as following.
$obj = json_decode($response->getBody());
$one_zero_one = $obj->data->{101};
Upvotes: 0