Fix PHP condition when decoding JSON - php

I'm decoding a json file using php.
In foreach statement I check if my cd_driver is in the array coming from the json file content. If it's in the array the script updates its month as expected. If not, the script writes the new driver into the json file.
Everything works fine but it's also executing the else condition after updating its month and adding the same driver to the json file. Why is this happening?
$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);
if($data == ""){
$newString = json_encode($dados);
file_put_contents('bsaldo.json', $newString);
}else {
foreach ($data as $key => $value) {
$mot = $value['cd_driver'];
$array = array();
array_push($array, $mot);
if(in_array($cd_driver, $array)){
$data[$key]['month'] = $cd_month;
$newString = json_encode($data);
file_put_contents('bsaldo.json', $newString);
}else {
array_push($data, $dados2);
$finalString = json_encode($data);
file_put_contents('bsaldo.json', $finalString);
}
}
}
json:
[
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
},
{
"cd_driver": "11835",
"Driver": "EDIVAN DE CASTRO VASSALO",
"month": "01",
"bsaldo": -7670
},
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
},
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
}
]
I had to adapt some things to work with php 5.1.

Your problem is that you are resetting the array on each iteration of the loop. Move it outside of the foreach, like so:
$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);
if($data == ""){
$newString = json_encode($dados);
file_put_contents('bsaldo.json', $newString);
}else {
$array = array(); # here it won't be continually reset and can accumulate values as intended.
foreach ($data as $key => $value) {
$mot = $value['cd_driver'];
array_push($array, $mot);
if(in_array($cd_driver, $array)){
$data[$key]['month'] = $cd_month;
$newString = json_encode($data);
file_put_contents('bsaldo.json', $newString);
}else {
array_push($data, $dados2);
$finalString = json_encode($data);
file_put_contents('bsaldo.json', $finalString);
}
}
}

Related

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

How to combine objects to array without removing duplicates in PHP

I have 3 objects and I want them to combine into 1 array. There are duplicate property names in objects, but I want them too (with renames property name). How can I do that?
$object1 = {
"id": "10",
"unit_number": "12565"
},
$object2 = {
"id": "20",
"full_name": "Lorem Ipsm"
},
$object3 = {
"id": "30",
"phone": "123456789"
}
I want the output like,
array = (
"id1" => "10",
"unit_number" => "12565",
"id2" => "20",
"full_name" => "Lorem Ipsm",
"id3" => "30",
"phone" => "123456789"
);
I have tried to assign them to one array like,
$arr = array();
$arr['obj1'] = $object1;
$arr['obj2'] = $object2;
$arr['obj3'] = $object3;
Now I thought of doing a foreach, but I am stuck. My actual object is too big. So there are many duplicates. Not just this one.
I think you can achieve this using below code,
$object1 = (object) ['id' => '10', "unit_number"=> "12565", "name" => 'Test name'];
$object2 = (object) ['id' => '20', "full_name"=> "Lorem Ipsm"];
$object3 = (object) ['id' => '30', "phone"=> "123456789", "name" => "test name 1"];
$array1 = (array) $object1;
$array2 = (array) $object2;
$array3 = (array) $object3;
function array_merge_dup_keys() {
$arrays = func_get_args();
$data = array();
foreach ($arrays as $a) {
foreach ($a as $k => $v) {
$key1 = check_key_exists($k,$data);
$data[$key1] = $v;
}
}
return $data;
}
function check_key_exists($key,$array,$loop_count=1)
{
if(array_key_exists ( $key , $array ))
{
$val = explode('_',$key);
$count = isset($val[1]) ? $val[1] : $loop_count;
$start_key = isset($val[0]) ? $val[0] : $key;
$key = $start_key.'_'.$loop_count;
$key = check_key_exists($key,$array,$count+1);
}
return $key;
}
$data = array_merge_dup_keys($array1 ,$array2,$array3);
The output ($data) of above code will be,
Array
(
[id] => 10
[unit_number] => 12565
[name] => Test name
[id_1] => 20
[full_name] => Lorem Ipsm
[id_2] => 30
[phone] => 123456789
[name_1] => test name 1
)
Maybe something like this? (untested, possible typos/syntax errors...)
// this looks like json, not PHP
// "object1": {
// "id": "10",
// "unit_number": "12565"
// },
// "object2": {
// "id": "20",
// "full_name": "Lorem Ipsm"
// },
// "object3": {
// "id": "30",
// "phone": "123456789"
// }
// here is a php array for that data
$objArray = array(
"object1" => array( "id"=>"10", "unit_number"=>"12565"),
"object2" => array( "id"=>"20", "full_name"=>"Lorem Ipsm"),
"object3" => array( "id"=>"30", "phone"=>"123456789")
);
$newArray = array();
foreach( $objArray as $key=>$value)
{
// the the id "append"
$idAppend = substr($key, strlen("object"));
foreach($value as $subkey=>$subvalue)
{
$newkey = $subkey;
if ( strcmp($subkey, "id") == 0 ) // it is the id string
{
$newkey = $subkey.$idAppend;
}
$newArray[$newkey] = $subvalue;
}
}

Trying create an associative array?

I have an array
Array
(
[0] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 1 BIMESTRE
)
[1] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 2 BIMESTRE
)
[2] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] =>3 BIMESTRE
)
)
Now I'm trying create an associative array to return JSON something like this:
"Materia":[{"descricao":"ARTE", "Notas":["1 BIMESTRE":10.00, "2 BIMESTRE":10.00, "3 BIMESTRE":10.00]}]
I don't know how I could create this associative array to this JSON result from this array that I'm posting.
I'm trying create like this but the result what I need does not return
$notas = '';
$materia = '';
foreach($lista as $value){
if($value["M_DESCRICAO"] != $materia){
$materia = $value["M_DESCRICAO"];
}
$notas = array("Descricao"=>$materia, "Notas"=>array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
$result = array("Materia"=>array($notas));
echo json_encode($result);
The result to what I'm trying is
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": {
"3 BIMESTRE": "10.00"
}
}
]
}
How could I create this associative array to return this JSON like I need ?
Edit
$notas = array();
$materia = '';
$materia_array = array();
foreach($lista as $value){
if($materia == ''){
$materia = $value["M_DESCRICAO"];
}
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas)));
$notas = array();
$materia = $value["M_DESCRICAO"];
}else{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
Result
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": [
{
"1 BIMESTRE": "10.00"
},
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "10.00"
}
]
},
{
"Descricao": "C.SOCIAIS",
"Notas": [
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "9.50"
}
]
},
{
"Descricao": "CIÊNCIAS E P. S.",
"Notas": [
{
"2 BIMESTRE": "9.50"
},
{
"3 BIMESTRE": "10.00"
}
]
}
]
}
I've refactored your last edit to remove some code duplication and complexity.
$result = array();
foreach ($lista as $value) {
$materia = $value['M_DESCRICAO'];
if (!isset($result[$materia])) {
$result[$materia] = array(
'Descricao' => $materia,
'Notas' => array()
);
}
$result[$materia]['Notas'][] = array(
$value['PE_DESCRICAO'] => $value['NT_NOTAFINAL']
);
}
$result = array('Materia' => array_values($result));
echo json_encode($result);
In addition to my comment, this would be the code to push all notes to an array as long as the M_DESCRICAO does not change, so the starting array $lista needs to be ordered first. Is this what you were after (code is not tested, office computer :-))?
$notas = $materia = null;
$result = $tmp = array();
$len = count($lista);
for ($i=0;$i<$len;$i++) {
$notas = array();
$materia = $lista[$i]["M_DESCRICAO"];
while (($materia == $lista[$i+1]["M_DESCRICAO"]) && ($i < ($len -1))) {
$notas[$lista[$i]["PE_DESCRICAO"]] = $lista[$i]["NT_NOTAFINAL"];
$i++;
}
// now $notas holds all corresponding entries
$tmp[] = array("Descricao"=>$materia, "Notas" => $notas);
}
$result = array("Materia"=>array($tmp));
echo json_encode($result);
I worked out an untested (there might be some errors, but logically it should work) piece of code, but it might help you:
$notas;
$materia = '';
$materia_array;
foreach($lista as $value){
if($materia == '')
$materia = $value["M_DESCRICAO"];
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas));
unset($notas); //<--------
$notas = array();//<--------
$materia = $value["M_DESCRICAO"];
}
else
{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]))
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
This should work for multiple M_DESCRICAO values

PHP Checkboxes in an array

When a form gets posted, I get some checkbox values like the below:
Array ( [chk0] => true ,
[chk1] => true,
[chk3] => true,
[chk1002] => on,
[chk1005] => on
)
Using PHP,How can I construct a JSON request like this by using the above variables?
"data":
[
{
"checkboxval": true,
"id": 0
},
{
"checkboxval": true,
"id": 1
},
{
"checkboxval": true,
"id": 3
},
{
"checkboxval": true,
"id": 1002
},
{
"checkboxval": true,
"id": 1005
}
]
Please note that my POST variables can have other form variables too, but all checkbox values will be named with the prefix "chk"
$output = array();
foreach ($input as $k => $v) {
$output[] = array(
'checkboxval' => !!$v,
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
foreach ($_POST as $k => $v) {
$output[] = array(
'checkboxval' => ($v=='on'? true : ($v=='off' ? false : !!$v)),
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
Credits to cletus who provided the basis for this code.
Have a look at the json_encode() php function. You'll have to massage your array a little to get the exact JSON format you're after.
Heres an example...
$_POST["chk1"] = "Hello";
$_POST["chk2"] = "World";
$jsonArray = array();
foreach($_POST as $key => $val){
if(preg_match("/chk/", $key)){
$jsonArray[$key] = $val;
}
}
$jsonArray = array("Data" => $jsonArray);
$json = json_encode($jsonArray);
echo "<pre>";
echo $json;
echo "</pre>";
Outputs this:
{"Data":{"chk1":"Hello","chk2":"World"}}
I haven't tested this yet, but maybe something like this:
$json = '"data": [';
$first = true;
foreach ($_POST as $k => $v){
if (preg_match('/^chk(\d+)$/', $k, $m)){
if ($first) $first = false; else $json .= ", ";
$json .= sprintf('{ "checkboxval" : %s, "id" : %s }', ($v && $v != "off") ? "true" : "false", $m[1]);
}
}
$json .= ']';

Categories