Recursively sorting a JSON array - php

I've looked a little and found an answer that partially does what I am interested in doing, see: Sorting a JSON array in PHP
I have some decoded JSON that looks like this, just a sample.
{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"
}
]
}
What I would like to do is sort everything alphabetically so that it is easier to read and uniform. So that what I would see is:
{
"accounts": [
{
"css": null,
"connected": 0,
"must_approve_upload": 0,
"password_expire": 90,
"settings": {
"link_external_whitelist": "",
"link_first_study_only": "0",
"other_ingress_tags": "",
"update_study_source_on_notify": "1"
},
"share_via_gateway": 0,
"vanity": "medpics"
}
],
"page": {
"more": 0,
"number": 1,
"rows": 5000,
}
"status": "OK"
}
Every element is sorted alphabetically. Is that possible ?

Pretty straightforward
$json = <<<JSON
{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"
}
]
}
JSON;
$json = json_decode($json, true);
function ksort_recursive(&$array) {
ksort($array);
foreach ($array as &$value) {
if (is_array($value)) {
ksort_recursive($value);
}
}
}
ksort_recursive($json);
print_r($json);
Proof of solution here
https://3v4l.org/qUAA0

Related

How to take a JSON content and return it in a wordpress function (php)?

I have a wordpress endpoint and I have some json data.
Unfortunately I dont know how to return this json data in the function. I tried json_decode but it doesn't return anything. Then endpoint works. If I use json_encode it returns data, but also include linebreaks and stuff. The problem seems to be with the syntax as it is already a complete json what I have. How can I return something that is already in json syntax?
add_action('wp_ajax_nopriv_inboundCall', 'testFunction');
add_action('wp_ajax_inboundCall', 'testFunction');
function testFunction() {
echo json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}');
die();
}
function testFunction() {
return json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}'); }
I saved the output of json_decode to a variable and then run json_encode on that variable. Now it seems to work.
function inboundCall() {
$json = json_decode('{
"topics": [
{
"_id": "1",
"name": "davisio",
"crdate": "2022-01-17T12:40:03.430Z",
"modified": "2022-01-17T12:40:03.430Z"
},
{
"_id": "2",
"name": "LoRaWAN",
"crdate": "2022-01-17T12:40:33.848Z",
"modified": "2022-01-17T12:40:33.848Z"
},
{
"_id": "3",
"name": "Kommunale Beziehungen",
"crdate": "2022-01-19T15:17:10.094Z",
"modified": "2022-01-19T15:17:10.094Z"
},
{
"_id": "4",
"name": "Test",
"crdate": "2022-03-31T13:29:41.799Z",
"modified": "2022-03-31T13:29:41.799Z"
}
],
"serviceState": {
"1": [
1,
0,
0,
1,
0,
0,
0,
1
],
"2": [
1,
0,
0,
0,
0,
0,
0,
1
],
"4": [
1,
0,
0,
0,
0,
0,
0,
1
]
}
}');
echo json_encode($json);
die();
}

How to prevent duplication of object inside by pushing it to the array in php?

I have question, is it possible not to duplicate the array object by looping on it? Right now I used laravel as my backend
I have here my response which is the exchange object duplicate itself.
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
]
Now my goal is to push the exchange without duplication:
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
}
]
Here is what my foreach loop like and how i push the array object.
$myArray = [];
foreach($exchange_check as $primary_array) {
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
array_push($myArray, (object)[
'exchange' => $primary_array,
'exchange_list' => $second_array,
]);
}
}
}
Thanks
You should add exchange data to array only once in first loop:
$myArray = [];
foreach($exchange_check as $primary_array) {
$idx = array_push($myArray, ['exchange' => $primary_array]);
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
//array_push() returns the new number of elements in the array,
//to get currently added array element we should subtract 1 from this number
$myArray[$idx-1]['exchange_list'][] = $second_array;
}
}
}
And in second loop add only exchange_list data to array.

How to get particular data from json url

I have following Json Data in php url
File name : house.php
{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"MAIN": 225,
"PHASE": 219418523,
"G": "7TH Division",
"GI": "2031892",
"DOOR": "8907",
"Gate": {
"RG": 2,
"BNS": "4 Window",
"BS": {
"SB1": 2
},
"TQ": [
{
"Key": 1,
"Value": {
"T1": 2
}
},
{
"Key": 2,
"Value": {}
}
],
"MR": -1,
"MS": 600
},
"AA": "81",
"AI": "8745524"
},
{
"MAIN": 300,
"PHASE": 219418523,
"G": "8TH Division",
"GI": "4526892",
"DOOR": "8877",
"GATE": {
"RG": 2,
"BNS": "5 Window",
"BS": {
"SB1": 2
},
"TQ": [
{
"Key": 1,
"Value": {
"T1": 2
}
},
{
"Key": 2,
"Value": {}
}
],
"MR": -1,
"MS": 600
},
"AA": "91",
"AI": "8758421"
}]}
I need particular data "G", "G1", "DOOR", "AA", A1" alone to display in my new php file :
completehouse.php in json format what code to give to get particular data.
<?php
$url="house.php";
$text = file_get_contents($url);
header('Content-Type: application/json');
echo $text;
?>
Currently i am using https://codebeautify.org/online-json-editor manually each time by using transform data
query : [*].{G: G, G1: G1, DOOR: DOOR, AA: AA, AI: AI} and getting output
{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"G": "7TH DIVISION",
"G1": "2031892",
"DOOR": "8907",
"AA": "81",
"AI": "8745524"
},
{
"G": "8TH DIVISION",
"G1": "4526892",
"DOOR": "8877",
"AA": "85",
"AI": "8759544"
}
]
}
Please someone help me to fix my manual work and save my time.
You can decode your json and then get the exact value of what you want.
$json = '....';
$parsed = json_decode($json,true);
$result = [];
if($parsed['Success']){ // check if your api json response is true.
foreach($parsed['Value'] as $val){
if($val['AI']> = 9000000){
$result[] = [
"G"=> $val['G'],
"GI"=> $val['GI'],
"DOOR"=> $val['DOOR'],
"AA"=> $val['AA'],
"AI"=> $val['AI']
];
}
// or what you want.
}
}
echo json_encode($result);
see demo
As you only need to manipulate the Value column so below code will keep all values same but get the specific columns from Value.
$url="house.php";
$text = file_get_contents($url);
$data = json_decode($text, true);
if ($data['Success'] === true) {
$v = [];
$columns = ["G", "GI", "DOOR", "AA", "AI"];
for ($i = 0; $i< count($data['Value']); $i++) {
foreach ($data['Value'][$i] as $key => $val) {
if (in_array($key, $columns)) {
$v[$key] = $val;
}
}
$data['Value'][$i] = $v;
}
}
$text = json_encode($data);

Loop in nested json array PHP

Sample of json string that receive by post is here:
[
{
"gc": [
{
"id": "1",
"ti": "title1",
"oid": 1,
"mid": "1-2",
"mc": 2,
"gct": 1,
"ma": 1,
"isu": 0
}
],
"gcm": [
{
"mid": "11",
"gcid":"1",
"sid": 58,
"msg": "msg1 ",
"sdt": "2018-11-12T13:58:24.627",
"ma": 20181112135822,
"isu": 0
},
{
"mid": "12",
"gcid":"1",
"sid": 58,
"msg": "msg2 ",
"sdt": "2018-11-12T13:58:24.627",
"ma": 20181112135822,
"isu": 0
}
],
"gcms": [
{
"id": "111",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "11"
},
{
"id": "112",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "11"
},
{
"id": "121",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "12"
},
{
"id": "122",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "12"
}
]
}
]
I use below code to loop in decoded array but only loop 1 time in array:
$json = json_decode($input, true);
foreach ($json as $value) {
$this->logger->info("Start update_new_data ->");
if (isset($value['gc'])) {
$this->logger->info("gc key exist");
foreach ($value["gc"] as $jObj) {
}
} else {
if (isset($value['gcm'])) {
$this->logger->info("gcm key exist");
foreach ($value["gcm"] as $jObj) {
}
} else {
if (isset($value['gcms'])) {
$this->logger->info("gcms key exist");
foreach ($value["gcms"] as $jObj) {
}
}
}
}
$this->logger->info("End update_new_data ->");
}
I want loop in array, if key is 'gc' loop in 'gc' array and loop again and if key is 'gcm' loop in 'gcm' array and if key is 'gcms' loop in 'gcms' array. I have to check the key because key mybe not exist in json string.
Test many code but can't solve problem.
How can i do this?
#mohammadi This Can work for you.
$json = json_decode($input, true);
$json = isset($json[0])?$json[0]:'';
$this->logger->info("Start update_new_data ->");
if(!empty($json)){
foreach ($json as $Key=>$value) {
if(isset($Key)){
if ($Key == "gc") {
$this->logger->info("gc key exist");
foreach ($value as $jObj) {
}
}
else if ($Key == "gcm") {
$this->logger->info("gcm key exist");
foreach ($value as $jObj) {
}
}
else if ($Key == "gcms") {
$this->logger->info("gcms key exist");
foreach ($value as $jObj) {
}
}
}
$this->logger->info("End update_new_data ->");
}
}
you can use this "$json = isset($json[0])?$json[0]:'';"line if you do not want to change the json structure because of the whole json date(array) inside a single array so you can get the first index of the array. if you change the json like this (shown below) then you did not require this "$json = isset($json[0])?$json[0]:'';"
$input = '{
"gc": [
{
"id": "1",
"ti": "title1",
"oid": 1,
"mid": "1-2",
"mc": 2,
"gct": 1,
"ma": 1,
"isu": 0
}
],
"gcm": [
{
"mid": "11",
"gcid":"1",
"sid": 58,
"msg": "msg1 ",
"sdt": "2018-11-12T13:58:24.627",
"ma": 20181112135822,
"isu": 0
},
{
"mid": "12",
"gcid":"1",
"sid": 58,
"msg": "msg2 ",
"sdt": "2018-11-12T13:58:24.627",
"ma": 20181112135822,
"isu": 0
}
],
"gcms": [
{
"id": "111",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "11"
},
{
"id": "112",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "11"
},
{
"id": "121",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "12"
},
{
"id": "122",
"ma": 1,
"mid": 58,
"sdt": "1",
"isu": 0,
"msf": 0,
"gcid": "1",
"cmid": "12"
}
]
}';
As per the json given in the question, the decoded array has single element which encloses all the elements. In that case, instead of looping through $json like: foreach ($json.., try looping through $json[0] like: foreach ($json[0]... And to get the key, you don't have to use array_keys, just run the loop with key like: foreach ($json[0] as $key => $value)...
I don't see any reason to use a loop for the outer array. Simply access the parts you want directly:
$json = json_decode($input, true);
$value = $json[0];
$this->logger->info("Start update_new_data ->");
if (isset($value['gc'])) {
$this->logger->info("gc key exist");
foreach ($value["gc"] as $jObj) {
}
}
if (isset($value['gcm'])) {
$this->logger->info("gcm key exist");
foreach ($value["gcm"] as $jObj) {
}
}
if (isset($value['gcms'])) {
$this->logger->info("gcms key exist");
foreach ($value["gcms"] as $jObj) {
}
}
$this->logger->info("End update_new_data ->");
This way you see your json structure more clearly (array inside an array).
Try to use array_keys for iteration:
$json = json_decode($input, true);
$json_keys = array_keys($json);
foreach ($json_keys as $json_key) {
$item = $json[$json_key];
foreach ($item as $row) {
foreach ($row as $subrow) {
echo isset($subrow['id']) ? $subrow['id'] : 'nope';
}
}
}

How can I create a spreadsheet with a json string via Google Spreadsheet API in PHP

I'm trying to create a spreadsheet which have 4 sheets and some format. I read the document of Google and knew that we can use method spreadsheets.create to do this. I made a json request body to test this API and it work but I don't know how to send this json in PHP.
This is my json string, you can test it in the Google Spreadsheet API document:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/create
{
"properties": {
"title": "Dự toán",
"defaultFormat": {
"verticalAlignment": "MIDDLE",
"wrapStrategy": "WRAP",
"textFormat": {
"fontFamily": "Arial",
"fontSize": 12
}
}
},
"sheets": [
{
"properties": {
"sheetId": 0,
"index": 0,
"title": "CP Xây lắp"
},
"merges": [
{
"sheetId": 0,
"startColumnIndex": 0,
"endColumnIndex": 5,
"startRowIndex": 0,
"endRowIndex": 1
},
{
"sheetId": 0,
"startColumnIndex": 0,
"endColumnIndex": 5,
"startRowIndex": 2,
"endRowIndex": 3
},
{
"sheetId": 0,
"startColumnIndex": 0,
"endColumnIndex": 5,
"startRowIndex": 3,
"endRowIndex": 4
},
{
"sheetId": 0,
"startColumnIndex": 0,
"endColumnIndex": 5,
"startRowIndex": 4,
"endRowIndex": 5
}
],
"data": [
{
"startRow": 0,
"startColumn": 0,
"rowData": [
{
"values": [
{
"userEnteredValue": {
"stringValue": "BẢNG TỔNG HỢP CHI PHÍ XÂY LẮP"
},
"userEnteredFormat": {
"horizontalAlignment": "CENTER"
}
}
]
},
{
"values": [
{}
]
},
{
"values": [
{
"userEnteredValue": {
"stringValue": "CÔNG TRÌNH: "
},
"userEnteredFormat": {
"horizontalAlignment": "CENTER",
"textFormat": {
"bold": true
}
}
}
]
},
{
"values": [
{
"userEnteredValue": {
"stringValue": "HẠNG MỤC: "
},
"userEnteredFormat": {
"horizontalAlignment": "CENTER",
"textFormat": {
"bold": true
}
}
}
]
},
{
"values": [
{
"userEnteredValue": {
"stringValue": "ĐỊA ĐIỂM: "
},
"userEnteredFormat": {
"horizontalAlignment": "CENTER",
"textFormat": {
"bold": true
}
}
}
]
}
],
"rowMetadata": [
{}
],
"columnMetadata": [
{}
]
}
]
}
]
}
Could somebody help me please ^^
I've done with it.
First just create a blank spreadsheet.
Then decode the json request string. We can create the json request follow this document: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
Then we use $service->spreadsheets->batchUpdate to send the request.
$requests = json_decode($json_request_string);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($requests);
$response = $service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);

Categories