PHP add key data to json - php

Have a nice day. I have created the following basics:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
}
}
}
I need to add the following lines to the same key:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
},
"h265": {
"url": "TEST",
"expire": 1649456380
}
}
}
But whatever I try, it does this to me:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
},
"0": {
"h265": {
"url": "TEST",
"expire": 1649456380
}
}
}
}
Here is some sample code:
$time = time();
$codec = "h265";
$url = "TEST";
$id = "1111";
$data = json_decode(file_get_contents('./data.json'), true);
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
$data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
file_put_contents('./data.json', $data);
Can someone advise me not to add the 0 key to me there

Change:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
To:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
$data[$id]['h265'] = $post_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'])
);

how to change the format of json value data in codeigniter

I am trying to display data for a plugin with a predefined json format, but after I try the data does not match the format how the problem?
JSON Required
[
{
latLng: [-6.17343444,1206.834234294],
name: 'XY'
},
{
latLng: [-6.1742343244,106.898987294],
name: 'XK'
}
]
Result my JSON
[
{
"latLng": "-6.17343444,1206.834234294",
"name": "XK"
},
{
"latLng": "-6.1742343244,106.898987294",
"name": "XY"
}
]
myscript PHP
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => $row->lat_long,
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
call JSON
$.parseJSON('<?php echo base_url().'mycontrollers';?>', function(datas) {
console.log(datas);
});
You can use explode() to transform the string "-6.17343444,1206.834234294" into an array [-6.17343444,1206.834234294]:
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => explode(',',$row->lat_long),
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
If you want to get floats (for all value in the JSON), you could use JSON_NUMERIC_CHECK:
json_encode($data, JSON_NUMERIC_CHECK);
Or, just for a specific value:
$latLng = explode(',', $row->lat_long);
$latLng = array_map('floatval', $latLng);
$data[] = array(
'latLng' => $latLng,
'name' => $row->city
);

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...

Invalid JSON Response in Datatable Codeigniter

I need an expert to fix this . This is my controller that load JSON .
foreach ($result->result() as $row){
$customer = $row->customer_name;
$ipull = $row->ip;
if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true){
$PING = $this->routerosapi->comm("/ping", array(
"address" => $ipull,
"count" => "2"
));
if( $PING['0']['packet-loss'] == 0){
$status = "Online";
} else {
$status = "Offline";
}
} else {
$this->session->set_flashdata('Connect_False','Failed To get');
redirect('tmikrotik/router_list');
}
$data = array(
'customer' => $customer,
'address' => $ipull,
'status' => $status
);
print json_encode($data);
}
And this is JSON response:
{"customer":"Trakindo Utama","address":"192.168.1.3","status":"Online"}{"customer":"Adira Finance","address":"192.168.1.10","status":"Offline"}{"customer":"Mandala Finance","address":"192.168.1.50","status":"Online"}
The problem is, when I load it into my data table, show popup invalid JSON response. This is my jQuery code
$(function () {
var table = $("#cpe-status").DataTable({
fixedColumns: true,
fixedHeader: true,
"pageLength": 10,
"paging": true,
"ajax": {
url: "./cpe",
type: "GET",
dataSrc: ""
},
"scrollX": true,
"aoColumns": [
{"data": "customer", "title": "Host"},
{"data": "address", "title": "Customer Name"},
{"data": "status", "title": "Registered"}
// {"data": "status", "title": "Status"}
]
});
// setInterval(function () {
// table.ajax.reload();
// }, 10000);
})
You are printing each result inside the loop. You should print the result as 1 array.
/* ============= Declare the data outside the loop ============= */
$data = array();
foreach ($result->result() as $row){
$customer = $row->customer_name;
$ipull = $row->ip;
if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {
$PING = $this->routerosapi->comm("/ping", array(
"address" => $ipull,
"count" => "2"
));
if( $PING['0']['packet-loss'] == 0){
$status = "Online";
} else {
$status = "Offline";
}
} else {
$this->session->set_flashdata('Connect_False','Failed To get');
redirect('tmikrotik/router_list');
}
/* ============= Push each result on an array ============= */
$data[] = array(
'customer' => $customer,
'address' => $ipull,
'status' => $status
);
}
/* ============= print result (outside the loop ) ============= */
print json_encode($data);

How to get join table data and pass inside array in php

I have two tables order and orderDetail. i have multiple delivery address in order detail table based on id of order table
i want to display id from order table and deliveryAddress from order detail table.i am getting below output when i print..
but unable to display delivery_address.please anyone can suggest how i display delivery_address..
{
"responseData": {
"status": 1,
"message": "",
"result": [
{
"Order": {
"id": "677",
"detail_location_instructions": "Near Inox"
},
"OrderDetail": [
{
"order_id": "677",
"delivery_address": "Smart Club Gimnasio - Avenida Álvarez Thomas, Buenos Aires, Autonomous City of Buenos Aires, Argentina"
},
{
"order_id": "677",
"delivery_address": "Lower Fort Street, Dawes Point, New South Wales, Australia"
}
]
},
{
"Order": {
"id": "680"
},
"OrderDetail": []
},
{
"Order": {
"id": "684"
},
"OrderDetail": [
{
"order_id": "684",
"delivery_address": "Four Seasons - Posadas"
}
]
}
]
}
}
below is my code
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data = $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => $value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address']
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}
You have to put the deliveryAddress in array
$c = array();
foreach ($data as $key => $value) {
$myOrders = [
'Id'=>$value['Order']['id'],
'deliveryAddress'=>[]
];
foreach($value['OrderDetail'] as $address){
$myOrders['deliveryAddress'][] = $address['delivery_address'];
}
$c[] = $myOrders;
}
Hope this will help
can you trying below code.
foreach ($data as $key => $value) {
$c[] = array(
'Order' => array(
'id'=>$value['Order']['id'],
'detail_location_instructions' => $value['Order']['detail_location_instructions'],
),
'OrderDetail' => array(
'order_id'=>$value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address'],
),
)
}
There is cases where you dont get the delivery address, in that case, you need to check if it exists first. use the Hash utility for that purpose.
I transformed the data to an array, in order for the class Hash to work.
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data =(array) $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => Hash::get($value, 'Order.id'),
'deliveryAddress' => current(Hash::extract($value, 'OrderDetail.{n}.delivery_address', array()))
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}

Categories