I've been looking all over the interwebz for a simple answer but can't find any. So, the question is:
I'm going to decode some JSON to see if a value exists; though, I don't think I'm doing it right. I want to check if the value of appid: 730 exists.
Here's the JSON:
{
response: {
game_count: 106,
games: [
{
appid: 10,
playtime_forever: 67
},
{
appid: 730,
playtime_forever: 0
},
{
appid: 368900,
playtime_forever: 0
},
{
appid: 370190,
playtime_forever: 0
},
]
}
}
This is what I want:
$json = file_get_contents('JSON URL HERE');
$msgArray = json_decode($json, true);
if (appid: 730 exists) {
...
}
Thanks, hope I explained enough.
PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
function is_valid_json( $raw_json ){ return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it. } In the above function, you will get true in return if it is a valid JSON.
Firstly, you have invalid json. See the comment in the string deceleration below (this might be a typo in your question).
$json = '{
"response": {
"game_count": 106,
"games": [
{
"appid": 10,
"playtime_forever": 67
},
{
"appid": 730,
"playtime_forever": 0
},
{
"appid": 368900,
"playtime_forever": 0
},
{
"appid": 370190,
"playtime_forever": 0
} // <------ note the lack of `,`
]
}
}';
$arr = json_decode($json, true);
foreach($arr['response']['games'] as $game) {
if($game['appid'] === 730) { // I would strictly check (type) incase of 0
echo "exists"; // or do something else
break; // break out if you dont care about the rest
}
}
example
We're just looping through the games array and checking its appid
. Then we just do something and then break the loop to prevent overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With