PHP: Add metadata array to JSON array - php

I've got the following JSON array with PHP:
"data": [
{
"RecordID": 1,
"OrderID": "53150-422",
...
},
{
...
},
I do this with:
echo json_encode(array('data' => $users),JSON_PRETTY_PRINT);
Now I want to add metadata to the array like this:
{
"meta": {
"page": 1,
"pages": 1,
"perpage": -1,
"total": 350,
"sort": "asc",
"field": "RecordID"
},
"data": [
{
"RecordID": 1,
"OrderID": "53150-422",
...
},
How to to this? Thanks in advance!

write code this way
<?php
$meta=[ "page"=> 1,
"pages"=> 1,
"perpage"=> -1,
"total"=> 350,
"sort"=> "asc",
"field"=> "RecordID"];
$users= [
"RecordID"=> 1,
"OrderID"=> "53150-422"
];
echo json_encode(array('meta'=>$meta,'data' => $users),JSON_PRETTY_PRINT);
?>

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 manually map collection using laravel/php and get total amount

I currently have the below json response that the API is returning. I am able to return it using Laravel Eloquent. There are several users and each user has a several receipts. A receipt has types and status. I want to try to get the total sum amount for each receipt that is related to its type and status. I was able to return the below json response using
$this->user->with('receipts')->has('receipts')->get(['id', 'name']);
I have tried using multiple laravel collections methods https://laravel.com/docs/5.8/collections#available-methods But I am still unable to get the desired response.
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"id": 1,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 2,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 3,
"user_id": 1,
"type_id": 2,
"status": 1,
"amount": 50
},
{
"id": 4,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 5,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 6,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 20
},
{
"id": 7,
"user_id": 1,
"type_id": 1,
"status": 1,
"amount": 10
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"id": 9,
"user_id": 2,
"type_id": 1,
"status": 0,
"amount": 20
}
]
}
]
I expect to get this:
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"performance and deleted": 220,
"performance and not deleted": 10,
"project and deleted": 60,
"project and deleted": 50
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"performance and deleted": 20,
"performance and not deleted": 0,
"project and deleted": 0,
"project and not deleted": 0
}
]
}
]
My main concern is to use laravel collection methods and easy to read code to get my expected result
In this way, I believe you get your expected result with nice readable code.
I'll assume that you have $users variable which contains a list of users in collection (And probably the receipts are already loaded).
// You need to name the keys as you desire. (I can't figure out the labels by the type_id and status numbers).
$statusPair = collect([
'performance and deleted' => [
'type_id' => 1,
'status' => 0,
],
'something' => [
'type_id' => 1,
'status' => 1,
],
'something 2' => [
'type_id' => 2,
'status' => 0,
],
'something 3' => [
'type_id' => 2,
'status' => 1,
],
]);
$data = $users->map(function ($user) use ($statusPair) {
$receipts = $user->receipts;
$sums = $statusPair->mapWithKeys(function ($pair, $statusLabel) use ($receipts) {
$filtered = $receipts;
foreach ($pair as $key => $value) {
$filtered = $filtered->where($key, $value);
}
$sum = $filtered->sum('amount');
return [
$statusLabel => $sum,
];
});
return [
'id' => $user->id,
'name' => $user->name,
'receipts' => $sums->toArray(),
];
});
i think this will help
$user->receipts->sum('amount');

php multidimension array dynamically

This is the static multidimension array and i converted to json.
$mailmsg = array(
'type'=> 'line',
'data' => array(
'labels' => array("1","2","3","4","5"),
'datasets' => array(array("label"=>"A","fill"=>"false","yAxisID"=>"A","borderColor"=>"#bae755","data"=>array(100, 96, 84, 76, 69)),array("label"=>"B","fill"=>"false","yAxisID"=>"B","borderColor"=>"#55bae7","data"=>array(1, 1, 1, 1, 0)),array("label"=>"C","fill"=>"false","yAxisID"=>"C","borderColor"=>"#e755ba","data"=>array(5, 15, 10, 10, 0)))),
' '=>array("scales"=>array("yAxes"=>array(array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn1"),"id"=>"A","type"=>"linear","position"=>"left"),array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn2"),"id"=>"B","type"=>"linear","position"=>"left"),array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn3"),"id"=>"C","type"=>"linear","position"=>"left")))
));
echo $json = json_encode((object)$mailmsg, JSON_NUMERIC_CHECK);
Result:
{
"type": "line",
"data": {
"labels": ["1","2","3","4","5"],
"datasets": [{
"label": "A",
"fill": "false",
"yAxisID": "A",
"borderColor": "#bae755",
"data": [100, 96, 84, 76, 69]
}, {
"label": "B",
"fill": "false",
"yAxisID": "B",
"borderColor": "#55bae7",
"data": [1, 1, 1, 1, 0]
}, {
"label": "C",
"fill": "false",
"yAxisID": "C",
"borderColor": "#e755ba",
"data": [5, 15, 10, 10, 0]
}]
},
"options": {
"scales": {
"yAxes": [{
"scaleLabel": {
"display": "true",
"labelString": "Prn1"
},
"id": "A",
"type": "linear",
"position": "left"
}, {
"scaleLabel": {
"display": "true",
"labelString": "Prn2"
},
"id": "B",
"type": "linear",
"position": "left"
}, {
"scaleLabel": {
"display": "true",
"labelString": "Prn3"
},
"id": "C",
"type": "linear",
"position": "left"
}]
}
}
}
I need to above static array to change dynamically using foreach.
just pass the reference to the specific data in the array:
foreach($mailmsg['data']['datasets'] as $key => $value){
}

Datatable Invalid JSON response error when my JSON is valid? PHP

My data table that is loading its body from another file with ajax is giving me the invalid JSON error, but when I check my developer tools under network responses my JSON is valid?
This is my PHP and SQL:
<?php
header('Content-Type: application/json');
$output = array('data' => array());
$query = "SELECT * FROM table";
$stmt = sqlsrv_query($sapconn2, $query);
$x = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$output['data'][] = array(
'col_1' => $x,
'ID' => $row['ID'],
'QuoteID' => $row['QuoteID'],
'CardCode' => $row['CardCode'],
'SlpCode' => $row['SlpCode'],
'SlpName' => $row['SlpName'],
'BandA' => $row['BandA'],
'NewPrice' => $row['NewPrice']
);
$x ++;
}
echo json_encode($output);
?>
This is my JSON thats returned in the browser:
{
"data": [
[1, 138, 25, "000123", "222", "test data", 222, 222],
[2, 144, 25, "000123", "132", "test data", 465, 789],
[3, 160, 25, "000123", "456132", "test data", 5599, 5499],
[4, 171, 25, "000123", "789", "test data", 7897, 989],
[5, 172, 25, "000123", "11111", "test data", 1, 11],
[6, 182, 25, "000123", "132166", "test data", 1323, 133],
[7, 183, 25, "000123", "135456", "test data", 1332132, 13213],
[8, 184, 25, "000123", "1321", "test data", 5643214, 6513]
]
}
EDIT:
var testTable = $("#testTable").DataTable({
processing: false,
serverSide: true,
dataType : 'json',
ajax: "test.php",
columns: [
{ "data": "col_1" },
{ "data": "ID" },
{ "data": "QuoteID" },
{ "data": "CardCode" },
{ "data": "SlpCode" },
{ "data": "SlpName" },
{ "data": "BandA" },
{ "data": "NewPrice" }
]
});
This is what datatable waits for:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
...
]
}
The "data" element is an array of objects, instead you pass an array of array.
You need something like that:
{
"data": [
{ "id": 1, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
{ "id": 2, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
]
}
EDITED:
$output['data'][] = array(
'col_1' => $x,
'col_2' => $row['ID'],
'col_3' => $row['QuoteID'],
'col_4' => $row['CardCode'],
'col_5' => $row['SlpCode'],
'col_6' => $row['SlpName'],
'col_7' => $row['BandA'],
'col_8' => $row['NewPrice']
);
When you make a request to a server-side script from DataTables with processing set to true then it sends this data.
When it returns data DataTables expects the data to follow these conventions.
You can either take these into account with your server-side script (there's a good example here.) or choose a different method for adding your data. If you perhaps set processing to false you might find everything just works as you expect.
Hope that helps.

Get information from multidimensional json in php

I am trying to get back information from a multidimensional json array but can't seem to get it right.
Below is an example of the output from the url which you can see yourself at http://109.255.189.130:3000/
{ "vnc_version": "2.1.0.0", "mod_version": "1.0.0.0", "server": { "name": "Pure Blood", "framework": "Microsoft Windows NT 6.2.9200.0" }, "stats": { "uptime": 53462.0, "uptime_peak": 53462.0, "online": 1, "online_max": 1, "online_peak": 2, "unique": 1, "unique_max": 1, "unique_peak": 2, "items": 111752, "items_max": 112259, "items_peak": 112259, "mobiles": 37963, "mobiles_max": 37976, "mobiles_peak": 37978, "guilds": 0, "guilds_max": null, "guilds_peak": 0 }, "players": [ { "info": { "id": 1, "name": "aN.Droid", "title": "", "profile": "", "guild_id": -1, "guild_abbr": "" }, "stats": [ ], "skills": [ ], "equip": [ ] } ], "guilds": [ ] }
What I would like to do is echo the name in the players array. There will be more than one player.
Can anyone please help me out here and point me in the correct direction to get this information?
I am very new to json so excuse my ignorance on the subject.
Thank you!
<?php
$json = '{ "vnc_version": "2.1.0.0", "mod_version": "1.0.0.0", "server": { "name": "Pure Blood", "framework": "Microsoft Windows NT 6.2.9200.0" }, "stats": { "uptime": 54383.3, "uptime_peak": 54383.3, "online": 1, "online_max": 1, "online_peak": 2, "unique": 1, "unique_max": 1, "unique_peak": 2, "items": 111672, "items_max": 112259, "items_peak": 112259, "mobiles": 37944, "mobiles_max": 37976, "mobiles_peak": 37978, "guilds": 0, "guilds_max": null, "guilds_peak": 0 }, "players": [ { "info": { "id": 1, "name": "aN.Droid", "title": "", "profile": "", "guild_id": -1, "guild_abbr": "" }, "stats": [ ], "skills": [ ], "equip": [ ] } ], "guilds": [ ] }';
$array = json_decode($json, true);
// you want 'true' as the second parameter so it tunrs this JSON data into a multidimensional array instead of objects.
foreach($array['players'] as $player){
print_r($player['info']);
//etc.. do what you want with each player
}
$json = '{ "vnc_version": "2.1.0.0", "mod_version": "1.0.0.0", "server": { "name": "Pure Blood", "framework": "Microsoft Windows NT 6.2.9200.0" }, "stats": { "uptime": 53462.0, "uptime_peak": 53462.0, "online": 1, "online_max": 1, "online_peak": 2, "unique": 1, "unique_max": 1, "unique_peak": 2, "items": 111752, "items_max": 112259, "items_peak": 112259, "mobiles": 37963, "mobiles_max": 37976, "mobiles_peak": 37978, "guilds": 0, "guilds_max": null, "guilds_peak": 0 }, "players": [ { "info": { "id": 1, "name": "aN.Droid", "title": "", "profile": "", "guild_id": -1, "guild_abbr": "" }, "stats": [ ], "skills": [ ], "equip": [ ] } ], "guilds": [ ] }';
$arr = json_decode($json, true);
foreach($arr["players"] as $player) print($player["info"]["name"]."<br/>");

Categories