I am getting array(0) in PHP yii2? - php

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" : {
}
}

Related

codeigniter create response array object

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

Modify array in php

This is my code for array creation
$insured_data['QuotaDtls']['Riskdtls'] = [
"InsuredName"=> "Testone",
];
$insured_data['Authenticate'] = [
'WACode' => '0000',
];
$insured_data['QuotaDtls'] = [
'ProductType'=> 'Individual'
];
Output:
{
"Authenticate": {
"WACode": "0000",
},
"QuotaDtls": {
"ProductType": "Individual",
"Riskdtls": {
"InsuredName": "Testone",
}
}
}
I want to do some modifications in this array tried many different ways but not able to do. This is done in code igniter, Please help.
{
"Authenticate": {
"WACode": "0000"
},
"QuotaDtls": {
"ProductType": "Individual",
"Riskdtls": [
{
"InsuredName": "Testone",
}
]
}
}
You need to make Riskdtls an array further in $insured_data['QuotaDtls']['Riskdtls'] like following
$insured_data['Authenticate'] = [
'WACode' => '0000',
];
$insured_data['QuotaDtls'] = [
'ProductType'=> 'Individual'
];
$insured_data['QuotaDtls']['Riskdtls'][] = [
"InsuredName"=> "Testone",
"entry2"=> "testdata2",
"entry3"=> "testdata3"
];
$json = json_encode($insured_data,JSON_PRETTY_PRINT) ;
printf("<pre>%s</pre>", $json);
The desired output would be achieved by encoding the array to JSON format using json_encode function and the final output would be following:
{
"Authenticate": {
"WACode": "0000"
},
"QuotaDtls": {
"ProductType": "Individual",
"Riskdtls": [
{
"InsuredName": "Testone",
"entry2": "testdata2",
"entry3": "testdata3"
}
]
}
}

how to make API response from php [duplicate]

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

Inserting JSON data into mysql using Codeigniter

I have json input as mentioned below am decoding the the json response and inserting it into the mysql database,Now am converting this into Codeigniter I am not able to understand how to write the controller and the model for the below code,Please let me know how to write the controller and model, also am providing the controller and model which is written by me
PHP Code
<?php
include ('config.php');
// read json file
date_default_timezone_set('Asia/Kolkata');
$timestamp = time();
$date_time = date("Y-m-d H:i:s", $timestamp);
$createdon = $date_time;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// $filename = 'employee.json';
// $json_data = file_get_contents($filename);
$json_data = $_POST['QUESTION'];
//convert json object to php associative array
$data = json_decode($json_data, true);
// print_r($data);
if (is_array($data) || is_object($data)) {
$jsonData = $data['DATA'];
$jsonAnswers = $data['ANSWERS'];
$drcode = $data['DATA']['DRCODE'];
$divcode = $data['DATA']['DIVCODE'];
$brdcode = $data['DATA']['BRDCODE'];
$prdcode = $data['DATA']['PRDCODE'];
// echo $drmobile." -- ";
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $data['ANSWERS'][$i]['ANSWER'];
$quecodes = $quecode[$i];
$answers = $answer[$i];
// echo $quecode[$i]." <--> ".$answer[$i]."<br/>";
$sql = "INSERT INTO ANSWERS(DRCODE,ADCODE,DIVCODE,BRDCODE,PRDCODE,ANSWERS,CREATEDON)VALUES ('$drcode', '$quecode[$i]', '$divcode', '$brdcode', '$prdcode', '$answer[$i]', '$createdon')";
$qur = mysql_query($sql);
if ($qur) {
$json = array("status" => 1, "msg" => "Data added Successfully!");
} else {
$json = array("status" => 2, "msg" => "Already Submitted");
}
}
// echo "<br/>-----------<br/>";
}
} else {
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
//close connection
?>
Json Input
{
"DATA": {
"DRCODE": "D40504",
"DIVCODE": 1,
"BRDCODE": 5,
"PRDCODE": 5
},
"ANSWERS": [{
"ADCODE": 1,
"ANSWER": "VERY GOOD"
}, {
"ADCODE": 2,
"ANSWER": "GOOD"
}, {
"ADCODE": 3,
"ANSWER": "SGH"
}, {
"ADCODE": 4,
"ANSWER": "NO"
}, {
"ADCODE": 5,
"ANSWER": "NO"
}, {
"ADCODE": 6,
"ANSWER": "CGHJ"
}]
}
Controller
public function feedback_post() {
$json_data = $this->post('QUESTION');
$data = $this->json_decode($json_data, true);
if (is_array($data) || is_object($data)) {
$jsonData = $this->$data['DATA'];
$jsonAnswers = $this->$data['ANSWERS'];
$drcode = $this->$data['DATA']['DRCODE'];
$divcode = $this->$data['DATA']['DIVCODE'];
$brdcode = $this->$data['DATA']['BRDCODE'];
$prdcode = $this->$data['DATA']['PRDCODE'];
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $this->$data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $this->$data['ANSWERS'][$i]['ANSWER'];
$quecodes = $this->$quecode[$i];
$answers = $this->$answer[$i];
}
$insert_array = array('DRCODE' => $drcode, 'DIVCODE' => $divcode, 'BRDCODE' => $speciality, 'PRDCODE' => $prdcode, 'ANSWER' => $answers, 'ADCODE' => $quecodes);
$feedback_data = $this->Rest_user_model->feedbacksubmission($insert_array);
if ($feedback_data) {
$message = ['status' => 1,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
} else {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
try this
public function feedback_post()
{
$objDate = new DateTime();
$data = json_decode($this->input->post('QUESTION'), true);
if (is_array($data))
{
foreach($data['ANSWERS'] AS $arrAnswer)
{
$arrInsertData =
[
'DRCODE' => $data['DATA']['DRCODE'],
'DIVCODE' => $data['DATA']['DIVCODE'],
'BRDCODE' => $data['DATA']['BRDCODE'],
'PRDCODE' => $data['DATA']['PRDCODE'],
'ADCODE' => $arrAnswer['ADCODE'],
'ANSWERS' => $arrAnswer['ANSWER'],
'CREATEDON' => $objDate->format('Y-m-d H:i:s'),
];
$feedback_data = $this->Rest_user_model->feedbacksubmission($arrInsertData);
$message = ($feedback_data) ? ['status' => 1, 'message' => 'Feedback Submitted Successfully'] : ['status' => 2, 'message' => 'Already Submitted'];
}
}
else
{
$message = ["status" => 0, "msg" => "Request method not accepted"];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
this is pretty much basic understanding of php - but you've to ask yourself - if you've multiple answers - what happens if one fails and one is successful ?
Because your sample php code is simply wrong...

How to fetch records for json in array using php?

$emparray=array();
while($row = mysqli_fetch_array($result,MYSQL_NUM))
{
foreach ($row as $key => $value)
{
if ($value == '')
{
$row[9] ='We follow-up you';
}
}
$emparray[] = array
('success' => true,
'message' => "audio saved Successfully!",
array('client_cname' => $row[2],
'future_followup' => $row[8],
'notes' => $row[9]));
}
** as you can see above this is my code for fetching records from db using while loop.
problem is im getting all records but with diffrent arrys. i want it in only 1 array with indexes**
[
{
"success": true,
"message": "audio saved Successfully!",
"0": {
"client_cname": "Hhhs",
"future_followup": "4 Jan 2017 05:17 PM",
"notes": "hey"
}
},
{
"success": true,
"message": "audio saved Successfully!",
"0": {
"client_cname": "Hcjc",
"future_followup": "4 Jan 2017 06:17 PM",
"notes": "hey"
}
}
]
above is my O/P
and i want it in below format please help me with the same.
{
"status": "true",
"message": "Audio Saved successfully!"
[
{
"client_cname": "Atul",
“future_followup": “”,
“notes": “”,
},
{
"client_cname": "Atul",
“future_followup": “”,
“notes": “”,
}
]
}
if i remove ->[ ] from $emparray then i will get only last row of table like below code
{
"success": true,
"message": "audio saved Successfully!",
"0": {
"client_cname": "Hcjc",
"future_followup": "4 Jan 2017 06:17 PM",
"notes": "hey"
}
}
but i want this kind of result with index 0,1,2 and so on.
please help me with the same. thanks in advance.
Here's what you need to do:
if(mysqli_num_rows($result)>0) { //if there are any results
//initialise the array with the first two values
$emparray = array(
'success' => true,
'message' => "audio saved Successfully!");
}
while($row = mysqli_fetch_array($result,MYSQL_NUM))
{
foreach ($row as $key => $value)
{
if ($value == '')
{
$row[9] ='We follow-up you';
}
}
//append each data item as an array
$emparray[] = array('client_cname' => $row[2],
'future_followup' => $row[8],
'notes' => $row[9]));
}
This will also automatically index all the other arrays numerically, starting from 0.
May be this is more better way to deal with.
$dataSet = array();
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
foreach ($row as $key => $value) {
if ($value == '') {
$row[9] = 'We follow-up you';
}
}
$dataSet[] = array('client_cname' => $row[2],
'future_followup' => $row[8],
'notes' => $row[9]);
}
$emparray = array
('success' => true,
'message' => "audio saved Successfully!",
'data' => $dataSet);
echo json_encode($emparray);

Categories