How to get nested pojo result like this one,
object
------object
------object
------------object
------array
This is I got from somewhere I forgot, but it has no code for make this result.
{
"success": true,
"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
"pie_statistics": {
"assigned": 120,
"opened": 212,
"in-progress": 100,
"completed": 320,
"done": 433,
"rejected": 111,
"expired": 332
},
"bar_months":[
"jan",
"feb",
"mar"
],
"bar_pending":[
100,
200,
300
],
"bar_rejected":[
140,
220,
340
],
"bar_completed":[
170,
290,
310
]
}
with my code like this
<?php
require "connection.php";
$query = "SELECT a.kondisi, k.area, COUNT(k.area) AS carea, COUNT(k.nrp) AS cnrp
FROM tb_absens AS a
INNER JOIN tb_karyawans AS k
ON a.nrp = k.nrp
WHERE a.kondisi = 'Sehat'
GROUP BY k.area";
$data = mysqli_query($conn, $query);
$json_array = array();
while($row = mysqli_fetch_array($data)){
array_push($json_array, array(
"success" => true,
"cnrp" => $row["cnrp"],
"area" => $row["area"],
"kondisi" => $row["kondisi"],
));
}
echo json_encode($json_array);
the result of mine like this
[
{
"success": true,
"cnrp": "1",
"area": "Administrator",
"kondisi": "Sehat"
},
{
"success": true,
"cnrp": "2",
"area": "AMK CPBP",
"kondisi": "Sehat"
},..
]
Yeah I know it's somekind old question, with many of questions similiar to. But I have no clue at all. I appreciate any help. Thanks.
If you want to get different json type into single json, you can split query first, and you execute each of query. To get nested object result like this
"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
try execute
while($row = mysqli_fetch_assoc($data)){
$json_arr['counter'][$row['a']] = $row['b'];
}
for nested array
"bar_months":[
"jan",
"feb",
"mar"
]
use this
while($row = mysqli_fetch_assoc($data)){
$json_arr2['bar_months'][] = $row_area['months'];
}
and to merge it to single json you can use
echo json_encode(array_merge($json_arr, $json_arr2));
Hope it can helps
Related
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');
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 the below
{
"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
}
]
}
]
You should be able to get the sum of amount with
$this->user->with(['receipts' => function($query) {
$query->selectRaw("SUM(amount) as amount, type_id, status, user_id")->groupBy('type_id', 'status', 'user_id');
}])->has('receipts')->get(['id', 'name']);
You can use collection methods to get the desired output
$this->user->with(['receipts' => function($query) {
$query->selectRaw("SUM(amount) as amount, type_id, status, user_id")->groupBy('type_id', 'status', 'user_id');
}])->has('receipts')->get(['id', 'name'])
->each(function ($user) {
$user->setRelation(
'receipts',
$user->receipts->mapWithKeys(function ($receipt) {
return [
$receipt->type_id . ' and ' . $receipt->status => $receipt->amount // format the key as you wish
];
})
);
})
You may use foreach and other loops to make the json you want!
use This function to convert your collection to the json you want :
public function convert(Collection $collection)
{
$result_collection = $collection;
$payment_collections = [];
foreach ($result_collection->receipts as $receipt)
{
$payment["type_id${receipt->type_id} and status${$receipt->status}"] = $receipt->amount;
}
$result_collection->receipts = $payment_collections;
return $result_collection;
}
And This is same way to get total amount. Just put an foreach and add each amount to a variable that initialized with 0;
and there is other ways like change toArray function in your Resource Collection.
I wrote the script assuming your data is a PHP array so you may change some part of my code.
For example you may change:
$row['receipts']
// To
$row->receipts
anyway
// The function in your controller
function index(){
$users=User::whereHas('receipts')->with('receipts')->get()->toArray();
return convert($users);
}
// The helper function
function convert($data){
$data=collect($data);
$allTypes=[];
$allStatuses=[];
return $data->each(function($row) use (&$allTypes,&$allStatuses){
$types=collect($row['receipts'])->pluck('type_id')->toArray();
$statuses=collect($row['receipts'])->pluck('status')->toArray();
$allTypes=array_unique(array_merge($allTypes,$types));
$allStatuses=array_unique(array_merge($allStatuses,$statuses));
})->map(function ($row,$index) use (&$allTypes,&$allStatuses){
$result=[];
$receipts=collect($row['receipts']);
foreach ($allTypes as $type){
foreach ($allStatuses as $status){
$result["type_id {$type} and status {$status}: "]=$receipts->where('type_id',$type)->where('status',$status)->sum('amount');
}
}
$row['receipts']=$result;
return $row;
});
}
I would like to be able to add to a JSON file via a online portal using PHP.
I have attempted to do this with the code below, How ever I am not familiar with PHP so I can not get further.
<?php
//Get the data from the url
$name = $_GET['name'];
$email = $_GET['email'];
// read json file
$data = file_get_contents('example.json');
// decode json
$json_arr = json_decode($data, true);
// add data
$json_arr[] = array(4, 'Name'=>$name, 'email'=>$email);
// encode json and save to file
file_put_contents('example.json', json_encode($json_arr));
?>
My attempt:
[{"0":4,"Name":"kieran","email":"ex#ex.com"}]
What I would want to add
//This is want the JSON should be
"0": {
"conditionName": "u",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"example#g.c"
],
"alertType": 1,
"emailProperty": 2,
"triggers": {
"0": {
"Property": 2,
"Value": "zk-reg",
"ComparisonType": "Equals"
}
}
},
This is the whole JSON:
{
"0": {
"conditionName": "u",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"example#g.c"
],
"alertType": 1,
"emailProperty": 2,
"triggers": {
"0": {
"Property": 2,
"Value": "zk-reg",
"ComparisonType": "Equals"
}
}
},
"1": {
"conditionName": "k",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"h#f.com"
],
"alertType": 1,
"emailProperty": 0,
"triggers": {
"0": {
"Property": 0,
"Value": "",
"ComparisonType": "Equals"
}
}
}
}
If I am understanding you correctly you want to do something like
<?php
// read json file in this case I just include it in the script for simplicity
$data = '{
"0": {
"conditionName": "u",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"example#g.c"
],
"alertType": 1,
"emailProperty": 2,
"triggers": {
"0": {
"Property": 2,
"Value": "zk-reg",
"ComparisonType": "Equals"
}
}
},
"1": {
"conditionName": "k",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"h#f.com"
],
"alertType": 1,
"emailProperty": 0,
"triggers": {
"0": {
"Property": 0,
"Value": "",
"ComparisonType": "Equals"
}
}
}
}';
// decode json
$json_arr = json_decode($data, true);
echo "Before Count " . count($json_arr);
// add data
//put the array of variables you want to add into its own var, add each variable you want, I've done the first two
$rowToAdd = array("conditionName" => "y", "ignoreFollowing" => false, "emailsThisSession" => 800, "recieverEmails" => array("h#f.com"));
//use array_push to add to the current array rather over-writing it
array_push($json_arr , $rowToAdd);
echo "After Count " . count($json_arr);
// encode json and save to file
file_put_contents('example.json', json_encode($json_arr));
?>
Try it:
//$data is data you wanto add.
$json_files = file_get_contents('example.json');
$tempArray = json_decode($json_files);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('example.json', $jsonData);
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);
?>
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.