This question already has answers here:
adding data into json with PHP
(2 answers)
Closed 3 years ago.
hello I made a post method with the API, I want to make a response like the following what can?
{
"status": 200,
"error": false,
"data": [
{
"id_kab": "56",
"id_prov": "1",
"kd_kab": "CGK10000"
}
]
}
what I did through POSTMAN now results like this
{
"id_kab": "56",
"id_prov": "1",
"kd_kab": "CGK10000"
}
this my code insert to database
public function submit_post() {
$data = array(
'id_kab' => $this->input->post('id_kab'),
'id_prov' => $this->input->post('id_prov'),
'kd_kab' => $this->input->post('kd_kab')
);
$insert = $this->db->insert('service', $data);
if ($insert) {
$arr=array(
'status' => 200,
'message' => 'Success'
);
header('Content-Type: application/json');
echo json_encode($arr,TRUE);
} else {
$this->response(array('status' => 'fail', 502));
}
}
how to change the response? thank you
From the response given, data should be given as an array, So please try the below code
$output = array();
$data = array();
$data[] = array(
'id_kab' => $this->input->post('id_kab'),
'id_prov' => $this->input->post('id_prov'),
'kd_kab' => $this->input->post('kd_kab')
);
$output["data"] = $data;
$output["status"] = 200;
$output["error"] = false;
echo json_encode($output); exit;
OutPut is as follows
{
"status": 200,
"error": false,
"data": [{
"id_kab": "56",
"id_prov": "1",
"kd_kab": "CGK10000"
}]
}
Demo
Related
This question already has answers here:
How to array_merge_recursive() an array?
(2 answers)
Closed 3 months ago.
I have an array like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_1": {
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
I want output like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
The answers that I found offered to search by name("function_1", "function_2"). But this does not suit me, the function will not always pass an array. I need exactly the "depth" or any other reasonable way.
Thank you!
To achieve your desired result, you could json-decode, recursively merge each individual subarray, then loop over that structure to push each item as a second-level array like this: (Demo)
$array = json_decode($json, true);
$merged = array_merge_recursive(...$array);
$result = [];
foreach ($merged as $key => $data) {
$result[] = [$key => $data];
}
var_export($result);
But I can't imagine getting any benefit from adding unnecessary depth to your result array. I recommend simply json decoding, then calling array_merge_recursive() with the spread operator: (Demo)
var_export(
array_merge_recursive(
...json_decode($json, true)
)
);
Output:
array (
'function_1' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
'function_2' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
)
Your data structure looks weird for the purpose you are trying to achieve I'm bored af tho and created this code for you
function combineElementsPerfunction($functions) {
$result = [];
$uniqueFunctions = [];
foreach ($functions as $function) {
$functionName = array_keys($function)[0];
$uniqueFunctions[] = $functionName;
}
$uniqueFunctions = array_unique($uniqueFunctions);
foreach ($uniqueFunctions as $uniqueFunction) {
$functionObjects = array_filter(
$functions,
function($function) use ($uniqueFunction) {
$functionName = array_keys($function)[0];
return $functionName === $uniqueFunction;
}
);
$elements = [];
foreach ($functionObjects as $functionObject) {
$function = array_shift($functionObject);
$elements = array_merge($elements, $function);
}
$result[] = [
$uniqueFunction => $elements
];
}
return $result;
}
function changeArr($data){
$box = $new = [];
foreach ($data as $v){
$key = array_key_first($v);
$i = count($box);
if(in_array($key, $box)){
$keys = array_flip($box);
$i = $keys[$key];
}else{
$box[] = $key;
}
$new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];
}
return $new;
}
I have the code below, but the result of the json response doesn't match
public function tes_get(){
$kode= $this->M_mymodel->tbl_kode('302'); // row
$res = array();
foreach ($kode as $key=> $value) {
$win = $this->M_mymodel->db_aa('302'); //row_array
$res = $this->M_mymodel->db_bb('302','LOSE'); //row_array
$res['data'][] = array(
'win' => $win['menang'],
'lose' =>$res['kalah']
);
}
$response = $this->set_response($res,200);
}
Below is the result of the response from the code I made above
{
"data": [
{
"win": "2",
"lose": "11"
}
]
}
How to make json response like below?
{
"data": [
{
"win": "2",
}
{
"lose": "11"
}
]
}
You can try :
$res['data'][] = array(
array('win' => $win['menang']),
array('lose' =>$res['kalah'])
);
I want to modify the response and get response as array but it's converted in object
I have tried this code:
$reports = mymodel::where('data_id', $id)
->get();
$response = array();
foreach($reports as $report){
$network_code_data[$report->created_date][$report->code][$report->network_code][] = $report;
$code_data[$report->created_date][$report->code] = ['code' => $report->code, 'name' => $report->name,
$tv_station_network_code_data[$report->created_date][$report->code]];
$response[$report->created_date] = ['uid' => $report->uid, 'created_date' => $report->created_date,
$code_data[$report->created_date]
];
}
return response()->json($response);
response of my code is good but its converted in object.
I want to get response like this
[ 0: { created_date: 2020/04/01,
data: [
0: { code: 1,
[
0: { network_code: 1, restofdata },
1: { network_code: 1, restofdata },
....
314: { network_code: 1, restofdata },
]},
1: {code: 2, [0: { network_code: 1, restofdata }]},
]
}, 1: { created_date: 2020/04/02 ...}, 2: { created_date: 2020/04/03 ...}]
Can any one help me?
I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)
I am getting array(0) as var_dump.
tbl_supplierOrderDetails['user_id']array(2) {
["tbl_supplierOrderDetails"]=>
array(0) {
}
["tbl_userContactDetails"]=>
array(0) {
}
}
Here is my API example using php yii2
public function actionSuggestions()
{
$listingId = Yii::$app->request->get('listing_id');
$apiUrl = "http://example.com:8800/api/Home/view_supplierOrderDetails?listing_id=".$listingId;
$suggestions = file_get_contents($apiUrl);
$suggestions = json_decode($suggestions, JSON_PRETTY_PRINT);
echo "tbl_supplierOrderDetails['user_id']";
//print_r($suggestions);
var_dump($suggestions);
exit;
return $this->render('suggestions' , array(
'listingId' => $listingId,
'suggestions' => $suggestions,
));
}
here is my api demo in json format.
{
"tbl_supplierOrderDetails": [
{
"num": 1,
"user_id": 3496,
"priority": "A.closed",
"no_of_times": 5,
"username": "eyuw",
"company_name": "djff",
"email": "abc#gmail.com",
"contact_no": "9999999999",
"origin": "abc",
"dest": "xyz",
"vehicle_class": "abc,
"vehicle_type": "abc",
"notes": "TCS_"
}]
"tbl_userContactDetails": [
{
"user_id": 500,
"contact_name": "Mr abc",
"contact_email": "abc#gmail.com",
"contact_mobile": 9999999999,
"contact_mobile2": null
}]
}
I want to display both this details in my html in different section . how can i do so by calling this api.
first of all, make sure that variable $suggestions contains what data you are expecting.
Your structure is completely wrong so, I would like to suggest you a good structure.
public function actionSuggestions() {
try {
$message = array();
$listingId = Yii::$app->request->get('listing_id');
if (!empty($listingId)) {
$apiUrl = "http://example.com:8800/api/Home/view_supplierOrderDetails?listing_id=" . $listingId;
$suggestions = file_get_contents($apiUrl);
$suggestions = json_decode($suggestions, JSON_PRETTY_PRINT);
//if $suggestions contains required data then you can return those data
$message = ['status' => 'success', 'message' => 'Data fetched succesfully', 'data' => $suggestions];
//else build an array like what format you want
} else {
$message = ['status' => 'failed', 'message' => 'Missing parameters.'];
}
} catch (\Exception $exception) {
$message = ['status' => 'failed', 'message' => "Some exception occured."];
}
return $message;
}
Here you can expect json output like the following:
{
"status" : "success",
"message" : "Data fetched succesfully",
"data" : {
}
}