i want php api responce in one array list - php

$MobileNo = $_POST['MobileNo'];
$query = "SELECT * FROM tblLotProcessStatus WHERE MobileNo = $MobileNo" ;
$result = sqlsrv_query($pdo,$query);
while ($row = sqlsrv_fetch_array($result,(SQLSRV_FETCH_ASSOC)))
{
if($row)
{
$status=array();
array_push($status,$row);
$response["status"] = $status;
$response["responce_code"] = 200;
$response["error_code"] = 0;
$response["error_msg"] = "status avialable";
echo json_encode($response);
}
JSON output:
{
"error": false,
"status": [
{
"id": 1,
"strPartyCode": "00000000",
"intLotID": "257949",
"MobileNo": "9879105144 ",
"Messages": "Lot No : 15023 on Loop Ager/Poly started.,Style:PIGMENT PRINT",
"status": 0,
"Type": "PF ",
"dtmDateTime": {
"date": "2016-02-22 12:00:00.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"strLotNo": "N 15023",
"strProcess": "Loop Ager/Poly,Style:PIGMENT PRINT",
"strStatus": " started."
}
],
"responce_code": 200,
"error_code": 0,
"error_msg": "status avialable"
}{
"error": false,
"status": [
{
"id": 2,
"strPartyCode": "00000000",
"intLotID": "246654",
"MobileNo": "9879105144 ",
"Messages": "Lot No : 8191 on Compacting complited.,Style:DYED",
"status": 0,
"Type": "PF ",
"dtmDateTime": {
"date": "2015-03-09 15:00:00.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"strLotNo": "N 8191",
"strProcess": "Compacting,Style:DYED",
"strStatus": " complited."
}
],
"responce_code": 200,
"error_code": 0,
"error_msg": "status avialable"
}

I think the problem is that you are adding all of the details to a new array and then outputing the json_encode()ed data each time. Instead you need to build up 1 array of data and encode it after loading all of the rows from the database...
$response = ["responce_code" => 200, "error_code" => 0,
"error_msg" => "status avialable" ];
while ($row = sqlsrv_fetch_array($result,(SQLSRV_FETCH_ASSOC)))
{
$response["status"][] = $row;
}
echo json_encode($response);
Just an aside - there may be a few spelling mistakes (assuming English spelling) in some of the data, perhaps
$response = ["response_code" => 200, "error_code" => 0,
"error_msg" => "status available" ];

Related

How do I correct duplicated json array in php

I have the following code that reads data from a mysql database. Unfortunately I dont seem to find a way of removing this "status": {
Here is the code snippet
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// database connection will be here
// include database and object files
include_once '../config/database.php';
include_once '../objects/status.php';
// instantiate database and status object
$database = new Database();
$db = $database->getConnection();
// initialize object
$status = new Status($db);
// query status
$stmt = $status->read();
$num = $stmt->rowCount();
// check if more than 0 record found
if($num>0){
// status array
$status_arr=array();
$status_arr["status"]=array();
// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row['name'] to
// just $name only
extract($row);
$status_item = array(
"id" => $status_id,
"name" => html_entity_decode($status_name),
"created" => $status_created,
"modified" => $status_modified,
"state" => $status_state
);
array_push($status_arr["status"], $status_item);
}
// set response code - 200 OK
http_response_code(200);
// show status data in json format
echo json_encode(
array("response_code" => 0, "response_message" => "Request processed successfully", "status" => $status_arr)
);
}
else{
// set response code - 404 Not found
http_response_code(404);
// tell the user no status found
echo json_encode(
array("response_code" => 1, "response_message" => "No status found.")
);
Which outputs this:
{
"response_code": 0,
"response_message": "Request processed successfully",
"status": {
"status": [
{
"id": "2",
"name": "Inactive",
"created": "2020-08-24 17:43:52",
"modified": "2020-08-24 13:43:52",
"state": "Active"
},
{
"id": "1",
"name": "Active",
"created": "2020-08-24 12:44:49",
"modified": "2020-08-24 05:44:49",
"state": "Active"
}
]
}
}
The desired output is:
{
"response_code": 0,
"response_message": "Request processed successfully",
"status": [
{
"id": "2",
"name": "Inactive",
"created": "2020-08-24 17:43:52",
"modified": "2020-08-24 13:43:52",
"state": "Active"
},
{
"id": "1",
"name": "Active",
"created": "2020-08-24 12:44:49",
"modified": "2020-08-24 05:44:49",
"state": "Active"
}
]
}
Note that in the desired output should not have "status": {} but should only have "status": []. What modification should i do to the above provided code?
echo json_encode(
array(
"response_code" => 0,
"response_message" => "Request processed successfully",
"status" => $status_arr["status"]
)
);

How display json records from database sorted by date and group by date

i need to display records from my database mysql grouped by date to JSON in PHP.
i have table :
--- transaction ---
- id
- date (Y-m-d H:i:s)
- user
- price
- product_id
- quantity
-------------------
And i wish display to JSON like this
{
"status": {
"code": 200,
"message": "Success"
},
"data": [
{
"date": "1 June 2020",
"detail": [
{
"id": 1,
"date_trx": "01-06-2020 15:22:54",
"user": "User A",
"price": 500,
"product_id": "Product A",
"quantity": 2
},
{
"id": 1,
"date_trx": "01-06-2020 17:22:54",
"user": "User B",
"price": 500,
"product_id": "Product H",
"quantity": 2
}
]
},
{
"date": "2 June 2020",
"detail": [
{
"id": 1,
"date_trx": "02-06-2020 15:22:54",
"user": "User A",
"price": 500,
"product_id": "Product A",
"quantity": 2
}
]
}
]
}
i have to tried some code from google or stackoverflow, but not like my wish
** EDIT **
this is my code have tried
$search = $call->query("SELECT * FROM transaction WHERE ORDER BY date DESC");
if($search->num_rows > 0){
$date = null;
$array = [];
while($record = $search->fetch_assoc()) {
$currentDate = date('Y-m-d', strtotime($record['tgl']));
if ($currentDate != $date) {
// echo "<h1>$currentDate</h1>";
$tgl = $currentDate;
}
$date = $currentDate;
// echo $record['rid']."<br>";
if(is_array($array) && $array['date'] != $tgl){
$arr = array(
'date' => $tgl,
'detail' => array(
'id' => $record['rid'],
'date_trx' => $record['tgl'],
'user' => $record['user'],
'price' => $record['price'],
'product_id' => $record['product'],
'quantity' => $record['quantity']
)
);
array_push($array, $arr);
}
}
$output = ['result' => true, 'data' => $array];
}
And this is respon from my code :
{
"result": true,
"data": [
{
"date": "2020-07-05",
"data": {
"id": "9924243",
"date_trx": "2020-07-05 07:03:58",
"user": "User A",
...
}
},
{
"date": "2020-06-01",
"data": {
"id": "9924243",
"date_trx": "2020-06-01 07:03:58",
"user": "User A",
...
}
},
{
"date": "2020-06-01",
"data": {
"id": "9924243",
"date_trx": "2020-06-01 07:03:58",
"user": "User A",
...
}
}
]
}
The respon from my code is not like my wishes, maybe you all can help me for wishes response
Iterate over results, add to your result a basic structure with 'date' and 'detail' under the date key if it doesnt exist and just add every row to correct 'detail'.
<?php
$db = new mysqli("localhost", "zz", "zz", "zz");
$query = "SELECT * FROM transaction ORDER BY date ASC";
$result = $db->query($query);
$data = [];
while($row = $result->fetch_assoc()) {
$date = new DateTime($row['tgl']);
if (!isset($data[$date->format('Y-m-d')])) {
$data[$date->format('Y-m-d')] = [
'date' => $date->format('j F Y'),
'detail' => [],
];
}
$data[$date->format('Y-m-d')]['detail'][] = [
'id' => $row['rid'],
'date_trx' => $date->format('d-m-Y H:i:s'),
'user' => $row['user'],
'price' => $row['price'],
'product_id' => $row['product'],
'quantity' => $row['quantity'],
];
}
$data = array_values($data);
var_dump(json_encode($data, JSON_PRETTY_PRINT));
Result:
string(892) "[
{
"date": "1 June 2020",
"detail": [
{
"id": "1",
"date_trx": "01-06-2020 15:22:54",
"user": "User A",
"price": "500",
"product_id": "Product A",
"quantity": "2"
},
{
"id": "2",
"date_trx": "01-06-2020 17:22:54",
"user": "User B",
"price": "500",
"product_id": "Product H",
"quantity": "2"
}
]
},
{
"date": "2 June 2020",
"detail": [
{
"id": "3",
"date_trx": "02-06-2020 15:22:54",
"user": "User A",
"price": "500",
"product_id": "Product A",
"quantity": "2"
}
]
}
]"

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);

How to add data to a JSON file

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);

Recursively sorting a JSON array

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

Categories