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);
Related
I've Json data in PHP which is:
{
"module": [
{
"jhooq-webserver-1": [
{
"source": ".//module-1"
}
]
},
{
"jhooq-webserver-2": [
{
"source": ".//module-2"
}
]
}
],
"provider": [
{
"aws": [
{
"access_key": "var.access_key",
"region": "var.web_region",
"secret_key": "var.secret_key"
}
]
}
]
}
All i wanted is to use recursive function to convert it to the below format (output):
provider "aws" {
region = "var.web_region"
access_key = "var.access_key"
secret_key = "var.secret_key"
}
module "jhooq-webserver-1" {
source = ".//module-1"
}
module "jhooq-webserver-2" {
source = ".//module-2"
}
Any help will be greatly appreciated.
I've tried using recursive function in php which i failed unfortunately failed. I'm unclear to use recursive function for my scenario.
You don't really need a recursive function to do this:
foreach($array as $blockName => $level2) {
foreach($level2 as $level3) {
foreach($level3 as $title => $level4) {
echo "$blockName \"$title\" {\n";
foreach($level4 as $level5) {
foreach($level5 as $key => $value) {
echo " $key = \"$value\"\n";
}
}
echo "}\n";
}
}
}
I have made function to display all my privileges against the menu
My Controller code below:
<?php
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
public function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row['is_checked'] = 1; // here is error
if ($row['parent_id'] == $parent_id) {
$children = $this->build_heirarchy($result_set, $row['id']);
if ($children) {
if ($children[0]['type'] == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row[$type] = $children;
}
$rs[] = $row;
}
}
return $rs;
}
}
?>
But I'm getting error of Cannot use object of type stdClass as array I'm so confused how I can make it happen and working
your help will be highly appreciated!
{
"data": [
{
"created_at": "2019-05-20 15:48:34",
"deletedAt": null,
"display_group": "patient",
"icon": "NULL",
"id": 297,
"isDeleted": null,
"is_checked": 1,
"parent_id": 0,
"priv_key": "can_access_patient",
"priv_title": "Patient",
"type": "menu",
"updated_at": "2019-05-20 15:48:34"
}
],
"message": "Privileges found!",
"status": true
}
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row->is_checked = 1; // here is error
if ($row->parent_id == $parent_id) {
$children = $this->build_heirarchy($result_set, $row->id);
if ($children) {
if ($children[0]->type == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row->{$type} = $children; // keys to object can only set using curly braces if variable
}
$rs[] = $row;
}
}
return $rs;
}
}
This is my final controller code and i have also shared the response with you can look into this and can let me know if there is any more changges
As per your suggestions and comments I modified your code, once check and let me know.
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
// add below line, keep your old code as it is and check
$privileges = json_decode(json_encode($privileges), true);
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
public function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row['is_checked'] = 1; // here is error
if ($row['parent_id'] == $parent_id) {
$children = $this->build_heirarchy($result_set, $row['id']);
if ($children) {
if ($children[0]['type'] == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row[$type] = $children;
}
$rs[] = $row;
}
}
return $rs;
}
}
EDIT
There is only record with parent id 0, so it will create only one parent record, and recursively it will have appended child data. Check this.
Now for parent id 1 it has 2 records in screenshot, so two elements will appended inside parent single most element.
Now for parent id 2 it has 4 records in screenshot, so 4 elements will be appended inside element with id 2.
This will go on inside to inside of every element considering parent
id.
Subsequently all data will be appended to every parent of it. So index is only one and data is appended recursively to its every relevant parent.
I hope I am clear.
if ($children)
{
if($children[0]->type=='menu')
$type = 'submenu';
else
$type = 'permission';
$row[$type] = $children;
}
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";
}
}
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
Ok I have banged my head for the last 24hrs and cannot figure this out after testing and reading SO. I have a JSON file that I need to parse and for some reason I cannot get the right combination of code to echo anything out other than "Array" or "Trying to get property of non-object" or "Invalid argument supplied for foreach()". Here is the full JSON that I am trying to iterate over. I need to print out the name of each 'project', the 'dataset' in each project, and the 'permissions' for each 'dataset'. I am building this JSON myself, so I can change the format if necessary.
$data = json_decode($json, true);
Outputs JSON below:
[
[
{
"projects":[
{
"project":"test-project-1",
"datasets":[
{
"dataset":"testing1",
"permissions":[
{
"role":"READER",
"google_group":"testing1#test.com"
}
]
},
{
"dataset":"testing2",
"permissions":[
{
"role":"OWNER",
"google_group":"testing2#test.com"
}
]
},
{
"dataset":"testing3",
"permissions":[
{
"role":"READER",
"google_group":"testing3#test.com"
}
]
},
{
"dataset":"testing4",
"permissions":[
{
"role":"WRITER",
"google_group":"testing4#test.com"
}
]
}
]
},
{
"project":"test-project-2",
"datasets":[
{
"dataset":"testing1",
"permissions":[
{
"role":"READER",
"google_group":"testing1#test.com"
}
]
},
{
"dataset":"testing2",
"permissions":[
{
"role":"READER",
"google_group":"testing2#test.com"
}
]
},
{
"dataset":"testing3",
"permissions":[
{
"role":"READER",
"google_group":"testing3#test.com"
}
]
},
{
"dataset":"testing4",
"permissions":[
{
"role":"READER",
"google_group":"testing4#test.com"
}
]
}
]
}
]
}
]
]
I have tried things like:
foreach($data->projects as $output)
{
echo $output->project . "\n";
foreach($output->datasets as $datasets)
{
echo $output->dataset . "\n";
}
}
Thank you for the help!
EDIT: Working code that parses the JSON above:
$projects = $json['projects'];
foreach ($projects as $project) {
echo $project['project'] . "<br>";
foreach ($json['projects'][0]['datasets'] as $datasets){
echo $datasets['dataset'] . "<br>";
foreach ($json['projects'][0]['datasets'][0]['permissions'] as $permissions){
echo $permissions['role'] . "<br>";
echo $permissions['google_group'] . "<br>";
}
}
}
Your json contains two nested arrays, which contain the object, you want. So first you could use something like [0][0] to get the associative array, which contains the project.
// ...
$projects = $json['projects'];
foreach ($projects as $project) {
echo "Project: " . $project['project'] . "\n";
foreach ($project['datasets'] as $dataset) {
echo "Dataset: " . $dataset['dataset'];
foreach ($dataset['permissions'][0] as $key => $value) {
// ...
}
}
}