PHP Select Data from Json - php

My JSON Data
{
"users": [
{
"userid": 1,
"username": "Admin",
"usermail": "admin#admin.com",
"authority": [
{
"authorityid": 1,
"authoritytext": "Admin",
"mission": [
{
"permission": "add"
},
{
"permission": "delete"
},
{
"permission": "move"
}
]
},
{
"authorityid": 1,
"authoritytext": "Super Admin",
"mission": [
{
"permission": "no add"
},
{
"permission": "no delete"
},
{
"permission": "only moderate"
}
]
}
]
}
]
}
MY PHP
foreach($result->users as $ok) {
foreach($ok->authority as $okey) {
foreach($okey->mission as $okeyokey) {
$test = $okeyokey->permission;
echo $test;
}
}
}
How to make this?
I want show parse json only authority{0} -> misson{0} show "permission" "add" please help me .
Maybe look ScreenShot >>>>>
I want filter {0}{1}{2} and select 0 -> show parse json
enter image description here

Is this what you are looking for?
<?php
$jsonData = '{
"users": [
{
"userid": 1,
"username": "Admin",
"usermail": "admin#admin.com",
"authority": [
{
"authorityid": 1,
"authoritytext": "Admin",
"mission": [
{
"permission": "add"
},
{
"permission": "delete"
},
{
"permission": "move"
}
]
},
{
"authorityid": 1,
"authoritytext": "Super Admin",
"mission": [
{
"permission": "no add"
},
{
"permission": "no delete"
},
{
"permission": "only moderate"
}
]
}
]
}
]
}';
$data = json_decode($jsonData);
echo($data->users[0]->authority[0]->mission[0]->permission);

You are getting objects and arrays confused
foreach($result->users as $currentUser){
$auths = $currentUser->authority;
foreach($auths as $currentAuth){
foreach($currentAuth->mission as $permission){
foreach($permission as $positionLabel => $permissionValue){
if($permissionValue == "add"){
// code here
}
}
}
}
}
Make sure you are using good labels. Dummy placeholders can be fine, but it makes tracking bugs really hard. I assume you want to check if they hold permission using a database, using PDO?
// array
$arr = ["this", "is", "an", "array"];
echo $arr[0] // prints out the word this.
$json = { "attribute": "value"}
echo $json->attribute // prints out the word value.
You can have arrays in JSON objects, and JSON Objects in arrays. How you access them are different.

Related

How to add item to an object in php

I have a nested object which is generated by a base data in a function. the data generated is several levels deep (data_tree)
To enter each children I use a recursive function.
What I want is to add the data of the children2 item to children and remove children2
Next I show the data_tree in JSON format to get an idea of ​​how the structure is. remember that the data_tree is an object
{
"data_tree": [
{
"code":"PE",
"country":"Peruvian",
"language" :"spanish",
"children":[
{
"code": "DEP1" ,
"region":"Tumbes",
"children": [
{
"code": "PRO1",
"province":"Contralmirante Villar"
}
],
"children2": [
{
"code": "PRO2",
"province":"Zarumilla "
}
]
},
{
"code": "DEP2" ,
"region":"Piura",
"children": [],
"children2": [
{
"code": "PRO4",
"province" :"Paita"
},
{
"code": "PRO5",
"province":"Sullana"
}
]
},
{
"code": "DEP3" ,
"region":"Lambayeque"
}
],
"children2":[
{
"code": "DEP4" ,
"region":"La Libertad"
},
{
"code": "DEP5" ,
"region":"Lima"
}
]
},
{
"code":"EC"
"country":"Ecuador",
"language" :"spanish",
"children":[
{
"code": "4" ,
"province":"Quito"
},
{
"code": "5" ,
"province":"Guayaquil"
}
],
"children2":[]
}
]
}
the recursive function i use is: if it has children it keeps iterating.
$traverse = function ($data_tree) use (&$traverse) {
foreach ($data_tree as &$node) {
if (empty($node->children)) { //if the children is empty
unset($node->children); //I remove the children to add it with the data of children2
$node->children =$node->children2;
unset($node->children2);//I delete children2
}else{
//in case I have data, how do I add the data from dechildren2 to children?
}
$traverse($node->children);
}
};
$traverse($data_tree);
return $data_tree;
All problem solved using json decode mean in associative array
$data_json='[{"children":[],"children2":[{"children":[],"children2":[{"code":"PRO1","children":[],"children2":[{"code":"PRO1"}]}]}]},{"children":[],"children2":[{"children":[{"code":"PRO1","children":[],"children2":[{"code":"PRO1"}]}]}]}]';
//$data_tree=;
$data_tree =json_decode($data_json,true);
// var_dump($data_tree);
$traverse = function (&$data_tree) use (&$traverse) {
foreach ($data_tree as &$node) {
// var_dump($node);
if (empty($node['children']) && !empty($node['children2'])) { //if the children is empty
// var_dump($node);
$node['children'] =$node['children2'];
unset($node['children2']);//I delete children2
}else{
//in case I have data, how do I add the data from dechildren2 to children?
}
if(isset($node['children'])){
$traverse($node['children']);
}
if(isset($node['children2'])){
$traverse($node['children2']);
}
}
};
$traverse($data_tree);
Output
[{"children":[{"children":[{"code":"PRO1","children":[{"code":"PRO1"}]}]}]},{"children":[{"children":[{"code":"PRO1","children":[{"code":"PRO1"}]}]}]}]

How I can read and update the nested JSON in PHP

I am new to PHP and have little experience with PHP arrays, I have this below JSON file.
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
I want to update the values for 'location', 'vmSize','sku','publisher','offer' in the above JSON,
"location" : "eastus"
"vmSize" : "Standard_D3_v2"
"sku" : "20h1-evd"
"publisher" : "MicrosoftWindowsDesktop"
"offer" : "windows-10"
I have tried to do the following to this but I am nowhere near navigating the array correctly.
$arr = json_decode($json2, true);
print_r($arr);
Can anyone please help here?
Just try this code
<?php
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
$arr = json_decode($json2, true);
$arr['location'] = "eastus";
$arr['properties']['hardwareProfile']['vmSize'] = "Standard_D3_v2";
$arr['properties']['storageProfile']['imageReference']['sku'] = "20h1-evd";
$arr['properties']['storageProfile']['imageReference']['publisher'] = "MicrosoftWindowsDesktop";
$arr['properties']['storageProfile']['imageReference']['offer'] = "WindowsServer";
$updatedJson = json_encode($arr);
print_r($updatedJson);
First you need to try json_decode to make an array from this json file and then based on the array schema you need to find the property that you want and update it and then again use the json_encode to make an json

I am not able to append one value in JSON response

Here i have one JSON response, in that response i am getting values like companyId,and divisionName etc..., now i want find companyId one means i want to find what is the company name, so written one function and also i got the company name, my problems is in this name i am not able to append same object
protected function getStates(){
// Cross validation if the request method is GET else it will return "Not Acceptable" status
if($this->get_request_method() != "GET"){
$response_array['status']='fail';
$response_array['message']='GET method only accept';
$response_array['data']='';
$this->response($this->json($response_array), 405);
}else{
$info_array = array(
"fields"=>"stateId,stateName,companyId",
"where"=>"stateStaus !='Inactive'"
);
$state_data = $this->GetRecords("state",$info_array);
if(count($state_data)>0) {
$companyId = $state_data['companyId'];
$check_info = array(
'fields'=>'companyName',
'where'=>'companyId = "'.$companyId.'" '
);
$companyName = $this->GetNameById('company',$check_info);
//$state_data['companyName'] = $companyName; //Company Name display
$response_array['status']='success';
$response_array['message']='Total '.count($state_data).' record(s) found.';
$response_array['total_record']= count($state_data);
$response_array['data']=$state_data;
$this->response($this->json($response_array), 200);
} else {
$response_array['status']='fail';
$response_array['message']='Record not found.';
$response_array['data']='';
$this->response($this->json($response_array), 506);
}
}
}
$this->response($this->json($response_array), 200); (i am getting response)
{
"status": "success",
"message": "Total 3 record(s) found.",
"total_record": 3,
"data": [
{
"stateId": "3",
"stateName": "Odisha",
"companyId": "1"
},
{
"stateId": "2",
"stateName": "Tamil Nadu",
"companyId": "1"
},
{
"stateId": "1",
"stateName": "Karnadaka",
"companyId": "1"
}
]
}
For finding companyName i wrote one function $companyName = $this->GetNameById('company',$check_info); here i am getting comapany name (Cibla).
My expected results
{
"status": "success",
"message": "Total 3 record(s) found.",
"total_record": 3,
"data": [
{
"stateId": "3",
"stateName": "Odisha",
"companyId": "1",
"companyName" : "Cibla"
},
{
"stateId": "2",
"stateName": "Tamil Nadu",
"companyId": "1",
"companyName" : "Cibla"
},
{
"stateId": "1",
"stateName": "Karnadaka",
"companyId": "1",
"companyName" : "Cibla"
}
]
}
Simple add your company name to division data array
$companyName = $this->GetNameById('company',$check_info);
$response_array['status']='success';
$response_array['message']='Total '.count($division_data).' record(s) found.';
$response_array['total_record']= count($division_data);
$division_data[0]['companyName'] = $companyName; //<--------------Add this line
$response_array['data']=$division_data;
$this->response($this->json($response_array), 200);
EDIT
As you have multiple division_data you need to loop over them to add companyName
change
$division_data[0]['companyName'] = $companyName;
to
foreach($division_data as $key=>$divisions)
{
$division_data[$key]['companyName'] = $companyName;
}

how to validate a json empty object in php

my php code works fine when it returns the result like this ->
{
"id": 267935,
"results": [
{
"key": "rc94yWXcyr0",
"name": "Trailer 1",
"site": "YouTube"
},
{
"key": "GZ0Bey4YUGI",
"name": "Official Trailer",
"site": "YouTube"
},
{
"key": "y1fZg0hhBX8",
"name": "Official Trailer 2",
"site": "YouTube"
}
]
}
but i get error
(Notice: Undefined variable: finaltrailers in ... )
when results return like this -->
{
"id": 392344,
"results": [
]
}
and this is my php code -->
$trailer = $json2['results'];
foreach($trailer as $trailers=>$keytrailers){
foreach($keytrailers as $alltrailers=>$allkeytrailers){
if($alltrailers == 'key'){
# $finaltrailers .= $allkeytrailers.',';
}
}
}
echo trim($finaltrailers,",");
how can i validate the empty array and give and error my self ? please help me thank you.
You have to define the variable to use it in trim.
Just add it at the beginning of your code.
$finaltrailers = '';
$trailer = $json2['results'];
foreach($trailer as $trailers=>$keytrailers){
foreach($keytrailers as $alltrailers=>$allkeytrailers){
if($alltrailers == 'key'){
# $finaltrailers .= $allkeytrailers.',';
}
}
}
echo trim($finaltrailers,",");

elasticsearch query by array of id result returned is not sorted by the array of id pass in

I am using elastica and below is my query :
$query = new Query();
$query->setSize(5);
$qb = new \Elastica\Query\Ids();
$qb->addId("id_5");
$qb->addId("id_3");
$qb->addId("id_4");
$qb->addId("id_1");
$qb->addId("id_2");
return $query->setQuery($qb)
I want the result return in the same order as what I passed in for example in this case it will be "id_5, id_3, id_4, id_1, id_2"
however what i get is the sorting is not the same as what I wanted
I see this as two solution
1. if you have id as part of document then you can do
POST indexName/_search
{
"sort": [
{
"_script": {
"type": "number",
"script": "sortOrder.indexOf(doc['Id'].value)",
"params": {
"sortOrder": [
"AVMX9sHTyNVr4SjF3oRt",
"AVMTc1fSyNVr4SjF3WpF",
"AVMYuGLOyNVr4SjF3rKm"
]
},
"order": "asc"
}
}
],
"query": {
"ids": {
"values": [
"AVMX9sHTyNVr4SjF3oRt",
"AVMTc1fSyNVr4SjF3WpF",
"AVMYuGLOyNVr4SjF3rKm"
]
}
}
}
If not then you need to update mapping for your type to be
{
"mappings": {
"YOUR_TYPE": {
"_id": {
"index": "not_analyzed"
}
}
}
}
Then you can use "script": "sortOrder.indexOf(doc['_id'].value)"

Categories