Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Json see if value exist

Tags:

json

php

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.

like image 525
m0nsterr Avatar asked Apr 25 '16 11:04

m0nsterr


People also ask

How check JSON key exists or not in PHP?

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.

How do I check if a string is in JSON format PHP?

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.


1 Answers

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.

like image 69
DevDonkey Avatar answered Nov 23 '22 10:11

DevDonkey