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"]
)
);
Related
I have a problem with JSON Array. How i can get value from 'orders' -> 'status'
This is body JSON body
{
"orders": [
{
"orderId": "F3MXBWMG61151028GUEST000P01",
"orderCreateDate": "2015-10-28T09:24:45.318+01:00",
"notifyUrl": "http://server/payuint2/main/notify2",
"customerIp": "127.0.0.1",
"merchantPosId": "200003",
"description": "TEST",
"currencyCode": "USD",
"totalAmount": "15000",
"status": "NEW",
"products": [
{
"name": "TEST",
"unitPrice": "15000",
"quantity": "1"
}
]
}
],
"status": {
"statusCode": "SUCCESS",
"statusDesc": "Request processing successful"
}
}
I'm trying to use the code for now
$order_info_payu = json_decode($response,true);
$order_status = $order_info_payu->orders->status;
or
$order_status = $order_info_payu['orders']['status'];
when I only use
$order_status = $order_info_payu['orders']
then I have the content, but how to capture 'status' from 'orders'?
Now its working.
$order_status = $order_info_payu->orders[0]->status;
echo $order_status;
Inside orders object you have an array thats why you need to add ..->orders[0]->..
see there is an
{
"orders": [ .... /* square brackets = an array inside the order object,*/
]
}
this square brackets means that after order object there is an array and then inside that array there are other objects.
$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" ];
I have a trouble with JSON in PHP.
I have a JSON structure like this (with some line is const and some line is variable)
{
"user": {
"lam": {---->variable
"\/lam\/files\/a": { ---->variable
"id": 9, ---->variable
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498", ---->variable
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=" ---->variable
}
}
}
}
}
I don't know how to write this content to file as JSON format like this.
And in a number of case, I must write append to this file and result must like this:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You could create an array, before to use json_encode():
Here is an example.
// prepare an array with variable (should come from database, or whatever)
$vars = [
[
'user' => 'lam',
'path' => '/lam/files/a',
'id' => 9,
'bucket' => 'lam-15215156681752265498',
'pass' => 'NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=',
],
[
'user' => 'lam',
'path' => '/lam/files/test',
'id' => 12,
'bucket' => 'lam-152153961597103330',
'pass' => 'MjdzcDlrenptcG5udzI2MLSQvuGIczY/SyHZVf9o7e8=',
]
];
// prepare data to be encoded.
$data = [];
// iterate over the variables,
foreach ($vars as $var) {
// prepare an array for the options
$options = [
"user" => "owncloud",
"bucket" => $var['bucket'], // fill with current variable
"password" => "",
"region" => "regionOne",
"service_name" => "swift",
"tenant" => "owncloud",
"timeout" => "30",
"url" => "http:\/\/controller:5000\/v2.0",
"password_encrypted" =>$var['pass'], // fill with current variable
];
$userdata = [
'id' => $var['id'], // fill with current variable
'class' => '\\OC\\Files\\Storage\\Swift',
'options' => $options, // append options
];
$name = $var['user'];
$path = $var['path'];
$data['user'][$name][$path] = $userdata ; // append to $data array
}
echo json_encode($data, JSON_PRETTY_PRINT);
Outputs:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You'll need to work with the data as an array (or object) as PHP won't work directly in JSON;
Get your current data from the file into an array:
$data = json_decode(file_get_contents($pathtojsonfile, true));
Append the new data to the array:
$data[] = $newdata;
Then save the newly appended data back to file.
file_put_contents($pathtojsonfile, json_encode($data));
I have this array $fields which is 2D. It's not a standard class and fetched from database. What I need to do is: Insert data into another array and give results like this (JSON encoded):
"fields": {
"0": [{
"field": "text",
"name": "link",
"label": "Link",
"required": true,
"type": "string"
}, {
"field": "xx",
"name": "xx",
"label": "xx",
"required": xx,
"type": "xx"
}],
"1": {
{
"field": "xx",
"name": "xx",
"label": "xx"
},
{
"field": "xx",
"name": "xx",
"label": "xx"
}
}
}
What I get is:
"fields": {
"0": [{
"field": "xx",
"name": "xx",
"label": "xx",
"required": xx,
"type": "xx"
}, {
"field": "xx",
"name": "xx",
"label": "xx",
"required": true,
"type": "xx"
}],
"1": {
"2": {
"field": "xx",
"name": "xx",
"label": "xx"
},
"3": {
"field": "xx",
"name": "xx",
"label": "xx"
},
}
}
Now I need to insert data to $f array and then $f array into array $r. To print like this "1": { or "0": { I use this:
$r = array(
'f' => (object) $f
);
The PHP code:
foreach($fields AS $c => $field) {
$f[$field['id']][$c] = array(
"field" => $field['field'],
"name" => $field['name'],
"label" => $field['label'],
);
if($field['required'] == "1") {
$f[$field['id']][$c]['required'] = true;
}
}
The issue mainly is $c thing, if I just do [] instead of [$c], it makes another array. I use the JSON encoded in JavaScript code and both the JSON encoded result works but I need the first one.
Your first JSON output is invalid. I hope it's just a typo from copying it into the question.
"1": {
{
should be "1": [ {.
If that's the case you can simply renumber the arrays after your code:
foreach($f as &$ff) $ff = array_values($ff);
unset($ff);
Or if you don't know or like references:
foreach($f as $key => $ff) $f[$key] = array_values($ff);
Then json_encode should create the output you want. (PHP arrays result in JSON arrays if the keys are numeric, start from 0, and have no holes; otherwise they will be encoded as JSON objects)
If you want to avoid another loop you could use:
foreach($fields AS $field) {
$f[$field['id']][] = array(
"field" => $field['field'],
"name" => $field['name'],
"label" => $field['label'],
);
//hacky way to get the key of the array just created
$c = count($f[$field['id']) - 1;
if($field['required'] == "1") {
$f[$field['id']][$c]['required'] = true;
}
}
Or create the array first and insert it in the end (a little cleaner imo):
foreach($fields => $field) {
$tmp = array(
"field" => $field['field'],
"name" => $field['name'],
"label" => $field['label'],
);
if($field['required'] == "1") {
$tmp['required'] = true;
}
$f[$field['id']][] = $tmp;
}
I am using Tropo Web API, to get result from a chat application, i redirected my JSON response to my server side PHP file(http://myhost.in/vj/app3.php?tropo-engine=json), the JSON response is coming correctly but i am not able to fetch data from that using PHP,
the JSON response is as follows..
{
"result": {
"actions":
[
{
"attempts": 2,
"concept": "mumbai",
"confidence": 100,
"disposition": "SUCCESS",
"interpretation": "mumbai",
"name": "city",
"utterance": "mumbai",
"value": "mumbai",
"xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result grammar=\"1#6ac61bfd.vxmlgrammar\"><interpretation grammar=\"1#6ac61bfd.vxmlgrammar\" confidence=\"100\"><instance>mumbai<\/instance><input mode=\"voice\" confidence=\"100\" timestamp-start=\"1970-01-01T00:00:00.000\" timestamp-end=\"1970-01-01T00:00:00.000\">mumbai<extensions><word-confidence> 100 <\/word-confidence><\/extensions><\/input><extensions><probability> 0 <\/probability><nl-probability> 0 <\/nl-probability><necessary-word-confidence> 0 <\/necessary-word-confidence><\/extensions><\/interpretation><\/result>\r\n\r\n"
},
{
"attempts": 1,
"concept": "cricket",
"confidence": 100,
"disposition": "SUCCESS",
"interpretation": "cricket",
"name": "sports",
"utterance": "cricket",
"value": "cricket",
"xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result grammar=\"2#6ac61bfd.vxmlgrammar\"><interpretation grammar=\"2#6ac61bfd.vxmlgrammar\" confidence=\"100\"><instance>cricket<\/instance><input mode=\"voice\" confidence=\"100\" timestamp-start=\"1970-01-01T00:00:00.000\" timestamp-end=\"1970-01-01T00:00:00.000\">cricket<extensions><word-confidence> 100 <\/word-confidence><\/extensions><\/input><extensions><probability> 0 <\/probability><nl-probability> 0 <\/nl-probability><necessary-word-confidence> 0 <\/necessary-word-confidence><\/extensions><\/interpretation><\/result>\r\n\r\n"
}
],
"callId": "b546e03db1ccfd2f0e8c58d970539501",
"complete": true,
"error": null,
"sequence": 1,
"sessionDuration": 11,
"sessionId": "ed6abc73b9c434385ea8cd8004c9ed0c",
"state": "ANSWERED"
}
}
the PHP code that i am using...
$json = file_get_contents("php://input");
$result = json_decode($json);
$value =$result->result->actions->value;
but i am getting null in the variable $value. How will get the value for city and sports as well..??
It is because $result->result->actions is an array. Try $result->result->actions[0]->value