Using PHP to find specific entry in JSON URL response - php

I am trying to find out whether a user is part of a Steam group. To do this, I'm using Steam's Web API, and using URL:
https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE
To get a JSON response of all groups that a user is part of.
Now I want to find out if they're part of my specific group with ID: 1111111 using PHP.
How would one do that? Currently I have the code being decoded like so:
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
This makes the $pretty variable contain the entire JSON response.
How would I use PHP to find the group ID in a response that looked like this?
{
"response": {
"success": true,
"groups": [
{
"gid": "4458711"
},
{
"gid": "9538146"
},
{
"gid": "11683421"
},
{
"gid": "24781197"
},
{
"gid": "25160263"
},
{
"gid": "26301716"
},
{
"gid": "29202157"
},
{
"gid": "1111111"
}
]
}
}
Can't figure it out.
Any help? :)

Use the below code to check whether user is exist in the response or not
$groupid = "1111111";
$is_exists = false;
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
foreach ($pretty['response']['groups'] as $key => $value) {
if($value['gid'] == $groupid) {
$is_exists = true;
break;
}
}
// check is_exists
Check that above variable $is_exists for true or false

$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList /v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result);
$s = $pretty->response->groups;
foreach($s as $value)
{
if((int) $groupid == $value->gid)
{
echo "Found";
}else
{
echo "Not found";
}
}

Related

rate not showing in WordPress

I am trying to echo out the rate but it's not showing. What is the actual reason. Can anyone help mw with it?
Here's the code
<?php
// Create the shortcode
function currency_conversion_shortcode() {
$url = "https://api.fastforex.io/convert?from=AED&to=NPR&amount=1&api_key=xxxxx-xxxx-xxxxx";// api key added on purpose
$result = file_get_contents($url);
$result = json_decode($result, true);
return $result['result'] . " NPR";
}
add_shortcode( 'currency_conversion', 'currency_conversion_shortcode' );
?>
Response data
{
"base": "AED",
"amount": 1,
"result": {
"NPR": 35.56,
"rate": 35.5597
},
"ms": 5
}
function currency_conversion_shortcode()
{
$url = "https://api.fastforex.io/convert?from=AED&to=NPR&amount=1&api_key=xxxxx-xxxx-xxxxx";
$result = file_get_contents($url);
$result = json_decode($result, true);
return $result['result']['rate'] . " NPR";
}
add_shortcode('currency_conversion', 'currency_conversion_shortcode');

How to add object inside object in php?

I am currently having problem creating a json response as I don't use PHP that much but can anyone help me create json like below:
{
"set_attributes":
{
"apikey": "some value",
},
"block_names": ["getdata"],
"type": "show_block",
"title": "go"
}
Here's my code:
$response = array();
$response['block_names'] = array();
$response['block_names'] = "getdata";
$response['type'] = "show_block";
$response['title'] = "go";
if ($db->studentLogin($username, $password)) {
$student = $db->getStudent($username);
$temp = array();
$temp['apikey'] = $student['api_key'];
$response['set_attributes'] = $temp['apikey'];
} else {
$temp = array();
$response['messages'] = array();
$temp['text'] = "Invalid username or password";
array_push($response['messages'],$temp);
}
echoResponse(200, $response);
It shows like this:
{
"block_names": "getdata",
"type": "show_block",
"title": "go",
"set_attributes": "f74911b29778adea86aa24d5ce85ff58"
}
But I want to add apikey = "f74911b29778adea86aa24d5ce85ff58" inside set_attributes and [] outside block_names just like obove. how can I do that?
try this:
$response['block_names'] = array("getdata");
...
$response['set_attributes'] = new \stdClass();
$response['set_attributes']->apikey = 'some_api_key';
https://3v4l.org/GDMKT#output

JSON Decode (PHP)

how can I Select the value of "success" from that json?:
{
"response": {
"success": true,
"groups": [
{
"gid": "3229727"
},
{
"gid": "4408371"
}
]
}
}
Thats my current code:
$result = json_decode ($json);
$success = $result['response'][0]['success'];
echo $success;
Thank you.
Regards
Here You go... with a Quick-Test Here:
<?php
$strJson = '{
"response": {
"success": true,
"groups": [
{
"gid": "3229727"
},
{
"gid": "4408371"
}
]
}
}';
$data = json_decode($strJson);
$success = $data->response->success;
$groups = $data->response->groups;
var_dump($data->response->success); //<== YIELDS:: boolean true
var_dump($groups[0]->gid); //<== YIELDS:: string '3229727' (length=7)
var_dump($groups[1]->gid); //<== YIELDS:: string '4408371' (length=7)
UPDATE:: Handling the value of success within a Conditional Block.
<?php
$data = json_decode($strJson);
$success = $data->response->success;
$groups = $data->response->groups;
if($success){
echo "success";
// EXECUTE SOME CODE FOR A SUCCESS SCENARIO...
}else{
echo "failure";
// EXECUTE SOME CODE FOR A FAILURE SCENARIO...
}
You are almost near to solution. place "true" as second argument for json_decode().
Eg:
$result = json_decode ($json, true);
$result['response']['success'];` -> to get the value of success.

Problems storing nested JSON objects

Could anyone assist me with how I can pass one JSON object as a field to another without having quotes added? Basically I have a function that needs to be able to append a 'header' to a set of data pre parsed into JSON in some cases or just parse the data in others.
Problem is everything works fine until I try to pass a JSON object to be stored as a "payload" for a header, at which point the JSON becomes invalid because of the extra set of quotations attached.
The object that I am trying to use is:
{
"header": {
"table": "user",
"action": "insert",
"opType": "string",
"message": "Insert sucessful for user: 6",
"start of records": false,
"end of records": true
},
"data": "[
{
"id": "6",
"Surname": "Peter",
"Forename": "Kane",
"Email": "pkane#a.co.uk",
"Personal_Email": "p.kane#gmail.com",
"Home_Phone_No": "01216045429",
"Work_Phone_No": "087852489",
"Mobile_Phone_No": "77245455598",
"Address_Line_1": "1aplace",
"Address_Line_2": "thistown",
"Address_Line_3": "Someplace",
"Address_Line_4": "whereever",
"Post_Code": "W549AJ",
"Mode_ID": "44",
"Route_ID": "g12",
"image": ""
}
]"
}
The problem is the quotes after the "data" key and before the last curley brace without these everything validates fine.
As I've said Im using PHP Ive tried regex expressions substring etc but nothing seems to work.
my PHP is as follows:
public function dataToJSON($operationType, $table, $action, $data, $message, $header = true, $firstRecord = null) {
if ((!($operationType) === 'recordSet') and (!($operationType === 'error')) and (!($operationType === 'string') )) {
throw new Exception("Operation type:" . ' ' . $operationType . ' ' . 'passed to the dataToJSON function not recogonised');
}
if (!(is_null($firstRecord))) {
$isFirstRecord = $firstRecord;
$isLastRecord = !$firstRecord;
} else {
$isFirstRecord = false;
$isLastRecord = false;
}
if ($header) {
$jsonData = array('header' => array(
'table' => "$table",
'action' => "$action",
'opType' => "$operationType",
'message' => "$message",
'start of records' => $isFirstRecord,
'end of records' => $isLastRecord),
);
} else {
$jsonData = array();
}
$recordSet = array();
if ($operationType === 'recordSet') {
while ($row = mysql_fetch_assoc($data)) {
array_push($recordSet, $row);
}
if ($header) {
$jsonData ['data'] = $recordSet;
return json_encode($jsonData);
} else {
return json_encode($recordSet);
}
} else if (($operationType === 'error') || ($operationType === 'string')) {
if ($header) {
$jsonData ['data'] = $data;
return stripslashes(json_encode($jsonData));
} else {
return $data;
}
}
}
in order to use / parse json, it needs to be valid json... and those **"** chars make it invalid.
paste and process here to see what i mean: http://jsonformat.com/
A JSON object is nothing more than a mere string. To achieve what you are trying to achieve, you would probably need to decode and then re-encode your JSON string:
$jsonData['data'] = json_decode($data, TRUE);

JSON Encode Help

Currently, I have a JSON encoded array that looks like this:
[
{
"username1": {
"post": {
"some_key" : "some_value"
}
}
},
{
"username1": {
"post": {
"some_key" : "some_value"
}
}
}
]
But how can I make it so that the json follows this pattern:
username -> array_of_posts -> post -> values
instead of the current pattern?
Thanks
Here is my current code:
while ($row = mysql_fetch_assoc($query)) {
$row['username'] = $username;
$returns[][$username]["post"] = $row;
}
}
echo json_encode(array_values($returns));
$returns[$username][] = $row;
echo json_encode($returns);

Categories