PHP Json see if value exist - 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.

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.

I find this solution quite straight forward:
$r='{
"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
}
]
}
}';
function find($arr, $id) {
if(!empty($arr))
foreach ($arr as $key => $value) {
if( isset( $value->appid ) && $value->appid == $id )
return true;
}
return false;
}
$obj = json_decode($r);
if( isset($obj) && isset($obj->response) ) {
if( isset($obj->response->games) && !empty($obj->response->games) )
$arr = $obj->response->games;
else
$arr = array();
} else {
echo "NOT valid found\n";
}
$appid = 730;
if( find($arr, $appid) )
echo "Appid $appid found\n";
else
echo "Appid $appid NOT found\n";
It is very convenient to parse and validate the results coming from other Web Services before accessing their data, so we avoid and development time.
I hope it is what you are looking for.

json_decode()
is actually going to return the decoded JSON. JSON is a string, decoded JSON is an array of objects.
You will need to iterate over that array of objects to inspect each.
$msgArray = json_decode($json);
foreach($msgArray->response->games as $game) {
if($game->appid == 730) {
// it exists
}
}

try this
$json = file_get_contents('JSON URL HERE');
$msgArray = json_decode($json, true);
foreach($msgArray['response']['games'] as $key => $value){
if ($value['appid'] == 730) {
//do something
}else{
// do else
}
}

Related

Equality comparison PHP

I'm doing this comparison below: $deviceKey == 'mobile' or $deviceKey == 'desktop'
public function syncPublisherIds (string $publisherId, Request $request):array
{
file_put_contents('/var/log/php/burner.log', json_encode($request->getContent()) . PHP_EOL, FILE_APPEND);
$idSyncConfig = json_decode($request->getContent());
$idSyncResponseObject = new \stdClass();
foreach($idSyncConfig as $deviceKey => $deviceValue) {
// file_put_contents('/var/log/php/burner.log', json_encode(gettype($deviceKey)) . ' '. json_encode($deviceValue) . PHP_EOL, FILE_APPEND);
// $deviceKey = json_encode($deviceKey);
// add device type to object
if ($deviceKey == 'mobile' or $deviceKey == 'desktop') {
$idSyncResponseObject[$deviceKey] = new \stdClass();
} else {
throw ((new BadRequestException("Platforms must be of type 'mobile' or 'desktop', you sent type of: $deviceKey"))->errorize());
}
}
}
For some reason it hits the else statement when they are seemingly the same:
"Platforms must be of type 'mobile' or 'desktop', you sent type of: \"mobile\""
This is a Laravel endpoint.
<?php
function testForLuke(string $requestContent): void
{
$idSyncConfig = json_decode(stripslashes($requestContent));
//print_r([$requestContent, $idSyncConfig]);
foreach ($idSyncConfig as $deviceKey => $deviceValue) {
//print_r([$deviceKey, $deviceValue]);
if ($deviceKey === 'mobile' || $deviceKey === 'desktop') {
echo "great success with deviceKey of '${deviceKey}'!\n";
} else {
echo "error condition throw exception\n";
}
}
}
testForLuke('{ "mobile": { "id": 1 } }');
testForLuke('{ "desktop": { "id": 1 } }');
testForLuke('{ "derptop": { "id": 1 } }');
testForLuke("{ \"mobile\": { \"id\": 1 } }");
testForLuke("{ \"desktop\": { \"id\": 1 } }");
For me yields:
great success with deviceKey of 'mobile'!
great success with deviceKey of 'desktop'!
error condition throw exception
great success with deviceKey of 'mobile'!
great success with deviceKey of 'desktop'!
The code seems to be working already, but is highly dependent on the structure of the provided JSON, so depending on the structure of the request you may still have issues, let us know.
Edit: After re-looking, it seems like you've got backslashes in your JSON request. Are you encoding it yourself? If so you should use json_encode($response, JSON_UNESCAPED_SLASHES);
If you can't control how it is encoded for whatever you reason, you could consider using:
$idSyncConfig = json_decode(stripslashes($requestContent));

Fragmenting incoming data with PHP Json

The form of the incoming json data:
{
"statusCode": 200,
"message": "success",
"result": [
{
"longitude": -87.06687,
"start_location_latitude": 20.63589,
"start_location_longitude": -87.06687,
"end_location_latitude": 20.63589,
"end_location_longitude": -87.06687,
"highlights": [
{
"title": "Oh Yes...Mezcal Shots",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpg"
},
{
"title": "Playa Del Carmen Beachfront",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpg"
},
{
"title": "Visit the Market",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg"
}
]
}
]
}
This incoming data is combined into a single line.
https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg
But what I want to do is to get the first 4 of these data, for example, by throwing them into separate variables and using them. However, I was never able to do that.
My code:
foreach($UnlockData as $highlights)
{
foreach($highlights as $SingleImage)
{
if(strlen($SingleImage['url']) > 3) {
echo $SingleImage['url'];
}
}
}
This will return the first 4 highlights from each entry in result. I am using the json object vs array because I find using it as objects makes for easier to read code.
<?php
$json = json_decode($incomingJSON);
foreach ($json->result as $result) {
$ctr = 0 ;
foreach($result->highlights as $highlight) {
if (strlen($highlight->url) < 5) continue;
echo "<P>" . $highlight->title. " - " . $highlight->url;
$ctr ++;
if ($ctr>3) break;
}
}
If there is ever only one result then just get all the url from highlights (not clear why the strlen):
$urls = array_column($array['result'][0]['highlights'], 'url');
foreach($urls as $url) {
if(strlen($url) > 3) {
echo $url;
}
}
If there are multiple result then get all the highlights and then get all the url from that:
$urls = array_column(array_column($array['result'], 'highlights'), 'url']);

PHP need to count how many instaneces of specific value in array

I have a JSON file which structure looks like this (very simplified):
[
{
"customerId": "M12345",
"houses": [
{
"id": "OBJ12345_1731321200",
"status": {
"id": "4",
"name": "Sold"
}
],
"plots": [
{
"id": "OBJ12345_1771637082",
"status": {
"id": "4",
"name": "Sold"
}
],
"projects": [],
"farms": [],
"commercialPropertys": [],
"condominiums": [],
"foreignProperties": [],
"premises": []
}
]
I have figured out how to count how many "houses" or "plots" there is:
$content = file_get_contents('estateList/estateList.json');
$GetEstateList = json_decode($content);
count($GetEstateList[0]["houses"]);
count($GetEstateList[0]["plots"]);
BUT Trying to figure out using php how to count how many objects which have a condition status(id:4)
I think you will need to use a loop in order to count the objects, i would use a foreach loop, bellow is an example :
$count = 0;
foreach ( $GetEstateList[0] as $key => $value){
if (isset($value['status']) && $value['status']['id'] === "4") {
$count++;
}
}
First, you need to enter the GetEstateList array, then you need to do a cycle for each type (for now types showed are plots and houses), then you need another cycle, because each type is an array of elements and can have more than one estate.
So, try this code:
// Counter variable for condition expressed after (status == 4)
$counter = 0;
// Enter the array and get `customerId`, `houses` and `plots`,
// but we only need the types of estate, so only `houses` and `plots`, in this case
foreach ( $GetEstateList as $estate_array => $array_attr ) {
// We only need `houses` and `plots` (increasing algorithm performance)
if ( $array_attr == "houses" || $array_attr == "plots" ) {
// We're checking all types of estates (all `houses` and all `plots`)
foreach ( $array_attr as $type => $parameter ) {
// So, we can get `status` of every estate
if ( $parameter == "status") {
// And finally we can get `id` for each estate `status`
if ( $parameter["id"] == "4" ) {
$counter++;
}
}
}
}
}
Notice: the code above cannot work if the written JSON structure is too different from the original.
I figured it out myself...
Maybe not the "correct" way but it works! :)
Feel free to comment on any improvement or modifications...
$StatusCount = 0;
foreach ($GetEstateList[0] as $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["status"]["id"] == "4") {
$StatusCount++;
}
}
}

How to get array index number by specific value

I have an array
Its a json data.
"score":[
{
"userId":"5",
"playtime":"1396369254",
"score":"25"
},
{
"userId":"3",
"playtime":"1396369246",
"score":"2"
},
{
"userId":"1",
"playtime":"1396369056",
"score":"12"
},
{
"userId":"2",
"playtime":"1396369240",
"score":"100"
}
],
I want to print array index number which userId value is 1.
Use a foreach as such:
foreach($array as $key=>$value) {
if($value['userId'] == 1) {
print $key;
break;
}
}

How to get different columns with JSON (PHP)?

I am very very new at PHP and I don't even know JSON. Also, I couldn't know how to express it in the question. My question is;
I need to make a JSON data with PHP with the data from database. So what my expected output is like;
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule": [ { "zone": "5", "position": "pre-roll" }, { "zone": "33", "width": 450, "height": 50, "startTime": "00:00:05", "duration": "15" } ], } }
What I wrote in PHP is;
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
}
$resultJSON .=json_encode($return_arr);
And my output is
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule":[{"zone":"3","position":"6"},{"zone":"2","position":"6"},{"zone":"4","position":"6"},{"zone":"5","position":"6"},{"zone":"6","position":"1","width":"468","height":"60"},{"zone":"7","position":"6","width":"468","height":"60"},{"zone":"8","position":"0","width":"120","height":"600"},{"zone":"9","position":"7","width":"120","height":"600"},{"zone":"10","position":"0","width":"120","height":"600"},{"zone":"11","position":"0","width":"728","height":"90"},{"zone":"12","position":"0","width":"120","height":"90"},{"zone":"13","position":"1","width":"468","height":"60"},{"zone":"14","position":"3","width":"468","height":"60"},{"zone":"15","position":"1","width":"560","height":"40"},{"zone":"16","position":"4","width":"468","height":"60"},{"zone":"17","position":"6","width":"468","height":"60"},{"zone":"18","position":"6","width":"468","height":"60"},{"zone":"19","position":"7","width":"468","height":"60"}] } }
If you noticed, even there shouldn't be width and height, there is. I only want the width and height when $row['delivery'] is 0,1 or 4. But, once it finds a value 0,1 or 4, then even if the next row is not 0,1 or 4, it prints width and height. Is there a way to fix this? I don't know any JSON and just started with PHP. Right now, I don't care about the missing tags like duration or writing pre-roll. I will take care of them after I fix this.
The problem is in your php. You don't reset the values of your array $row_array, so the first time the condition is true, the values of height and width are kept in the array.
You can fix it this way :
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
// Add this line to reset the array and reset width / height
$row_array = array();
}
$resultJSON .=json_encode($return_arr);

Categories