John Davidson

php - search through JSON Object for specific key

0 comments
Message:


I'm getting a JSON response from an API provider which I can't change, and there are lots of nested objects in the response and then there is an object which I need, below is just the example of response actual response has a lot of nested objects and then the match object,


I can easily access the match object but in some case, the API provider add some more object above it as shown in the 2nd response where he added the group and then there is match object which I need,


still by using some if, else we can get through it.


but are there any methods or ways available that can directly give me access to the match object or can find the match object?


I'm using laravel 5.8


and tried some of the collection methods none of them work on objects.


in actual response, I have to go 7 steps nested.


//1nd API response
[{
"version": "2.258.2",
"sport": "badminton",
"lang": "en",
"generated_utc": "2021-07-28T13:58:16+00:00",
"method": {
"method_id": "258",
"name": "get_matches"
"match" : {
score_a:0,
score_b:1
}
}
}]

//2nd API response
[{
"version": "2.258.2",
"sport": "badminton",
"lang": "en",
"generated_utc": "2021-07-28T13:58:16+00:00",
"method": {
"method_id": "258",
"name": "get_matches"
"group":{
"match" : {
score_a:0,
score_b:1
}
}
}
}]

Thank You!



My Answer:
// Example response with match object directly
$response = '{
"match": {
"id": 1,
"name": "Match 1"
}
}';

$data = json_decode($response, true);

if (isset($data['match'])) {
$match = $data['match'];
// Access match object here
echo $match['name'];
} else {
echo "Match object not found";
}

// Example response with group object added
$response = '{
"group": {
"id": 1,
"name": "Group 1",
"match": {
"id": 2,
"name": "Match 2"
}
}
}';

$data = json_decode($response, true);

if (isset($data['group'])) {
$group = $data['group'];
if (isset($group['match'])) {
$match = $group['match'];
// Access match object here
echo $match['name'];
} else {
echo "Match object not found";
}
} else {
echo "Group object not found";
}

Rate this post

4 of 5 based on 2162 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us