php to connect and get all rows
$query = 'SELECT * FROM cdr';
$sql = $remotedbh->prepare($query);
$sql->execute();
$dblist = $sql->fetchAll(PDO::FETCH_ASSOC);
if($sql->rowCount() > 0){
header('Content-type: application/json');
echo json_encode($dblist,JSON_FORCE_OBJECT);
}
else {
echo 0;
}
The problem is my json looks like this
{
"0": {
"calldate": "2013-08-14 11:41:28",
"clid": "\"tet\" <1002>",
"src": "1002",
"dst": "8834404",
"dcontext": "from-internal",
"channel": "SIP\/1002-00000000",
"dstchannel": "IAX2\/voipms-6749",
"lastapp": "Dial",
"lastdata": "IAX2\/voipms\/14798834404,300,",
"duration": "7",
"billsec": "0",
"disposition": "NO ANSWER",
"amaflags": "3",
"accountcode": "",
"uniqueid": "1376498488.1",
"userfield": "",
"did": "",
"recordingfile": "",
"cnum": "",
"cnam": "",
"outbound_cnum": "",
"outbound_cnam": "",
"dst_cnam": ""
},
"1": {
"calldate": "2013-08-14 11:42:55",
"clid": "\"Rtest\" <1002>",
"src": "1002",
"dst": "9187755592",
"dcontext": "from-internal",
"channel": "SIP\/1002-00000001",
"dstchannel": "IAX2\/voipms-121",
"lastapp": "Dial",
"lastdata": "IAX2\/voipms\/19187755592,300,",
"duration": "494",
"billsec": "485",
"disposition": "ANSWERED",
"amaflags": "3",
"accountcode": "",
"uniqueid": "1376498575.3",
"userfield": "",
"did": "",
"recordingfile": "",
"cnum": "",
"cnam": "",
"outbound_cnum": "",
"outbound_cnam": "",
"dst_cnam": ""
},
"2": {
so on so forth
I also am having the problem of everytime it pulls all the information a row is only half complete so it has a problem with that aswell, I was thinking of finding away to query the everything that is 5 minutes or older.
It's including the row numbers as you're using JSON_FORCE_OBJECT
Remove it and it it'll successfully return as an array.
e.g.
echo json_encode($dblist);
JSON_FORCE_OBJECT option in json_encode() forces the array to a json object with its indexes as keys. Removing that might get working for you.
update :
because while testing with a sample array
$test = array(array("calldate"=> "2013-08-14","src"=> "1002"),
array("calldate"=> "2013-08-18","src"=> "1003")
);
echo json_encode($test,JSON_FORCE_OBJECT);
//Outputs :
//{"0":{"calldate":"2013-08-14","src":"1002"},"1":{"calldate":"2013-08-18","src":"1003"}}
and
echo json_encode($test);
//Outputs :
// Gave me [{"calldate":"2013-08-14","src":"1002"},{"calldate":"2013-08-18","src":"1003"}]
so using just
echo json_encode($dblist);
should do the trick
Related
I'm trying to extract some JSON contained in of my XML file and then retrieve the values.
My XML is :
<Vehicle xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://regcheck.org.uk">
<vehicleJson>{
"Description": "RENAULT SCÉNIC III",
"RegistrationYear": "2016",
"CarMake": {
"CurrentTextValue": "RENAULT"
},
"CarModel": {
"CurrentTextValue": "SCÉNIC III"
},
"EngineSize": {
"CurrentTextValue": "5"
},
"FuelType": {
"CurrentTextValue": "DIESEL"
},
"MakeDescription": {
"CurrentTextValue": "RENAULT"
},
"ModelDescription": {
"CurrentTextValue": "SCÉNIC III"
},
"Immobiliser": {
"CurrentTextValue": ""
},
"IndicativeValue": {
"CurrentTextValue": 0
},
"DriverSide": {
"CurrentTextValue": ""
},
"BodyStyle": {
"CurrentTextValue": "MONOSPACE COMPACT"
},
"RegistrationDate": "2016-06-24",
"ImageUrl": "http://immatriculationapi.com/image.aspx/#UkVOQVVMVCBTQ8OJTklDIElJSQ==",
"ExtendedData": {
"anneeSortie": "2016",
"boiteDeVitesse": "",
"carburantVersion": "D",
"carrosserieVersion": "",
"classeSra": "",
"libVersion": "1.5 dCi 1461cm3 110cv ",
"libelleModele": "SCÉNIC III",
"marque": "RE",
"modele": "",
"produit": "",
"puissance": "5",
"version": "",
"cleCarrosserie": "",
"groupeSra": "",
"nbPlace": "5",
"datePremiereMiseCirculation": "24062016",
"questionBatterie": "",
"electrique": "",
"genre": "",
"typeVehicule": "",
"numSerieMoteur": "VF1JZ890H55864144",
"valeurANeufSRA": "",
"niveauRisqueVol": "",
"protectionConstructeur": "",
"puissanceDyn": "110",
"segmentVeh": "",
"KtypeId": "5853",
"EngineCC": "1461",
"Co2": "105",
"Cylinders": "4",
"CNIT": "M10RENVP472E768"
}
}</vehicleJson>
<vehicleData>
<Description>RENAULT SCÉNIC III</Description>
<RegistrationYear>2016</RegistrationYear>
<CarMake>
<CurrentTextValue>RENAULT</CurrentTextValue>
</CarMake>
<CarModel>SCÉNIC III</CarModel>
<BodyStyle>
<CurrentTextValue>MONOSPACE COMPACT</CurrentTextValue>
</BodyStyle>
<EngineSize>
<CurrentTextValue>5</CurrentTextValue>
</EngineSize>
<NumberOfDoors>
<CurrentValue>5</CurrentValue>
</NumberOfDoors>
<Transmission>
<CurrentValue />
</Transmission>
<FuelType>
<CurrentTextValue>DIESEL</CurrentTextValue>
</FuelType>
<Immobiliser>
<CurrentTextValue />
</Immobiliser>
<NumberOfSeats>
<CurrentValue>5</CurrentValue>
</NumberOfSeats>
</vehicleData>
</Vehicle>
Step 1: I'm looking to retrieve the Description and some values contained in ExtendedData :
$xml = simplexml_load_string($my_xml) or die("Error: Cannot create object");
$infos_plaque = json_encode($xml->vehicleJson); // The attribute where the JSON is stored
$array = json_decode($infos_plaque);
echo "<pre>";
print_r($array);
echo "</pre>";
This $array return :
stdClass Object
(
[0] => {
"Description": "RENAULT SCÉNIC III",
"RegistrationYear": "2016",
"CarMake": {
"CurrentTextValue": "RENAULT"
},
"CarModel": {
"CurrentTextValue": "SCÉNIC III"
},
"EngineSize": {
"CurrentTextValue": "5"
},
"FuelType": {
"CurrentTextValue": "DIESEL"
},
"MakeDescription": {
"CurrentTextValue": "RENAULT"
},
"ModelDescription": {
"CurrentTextValue": "SCÉNIC III"
},
"Immobiliser": {
"CurrentTextValue": ""
},
"IndicativeValue": {
"CurrentTextValue": 0
},
"DriverSide": {
"CurrentTextValue": ""
},
"BodyStyle": {
"CurrentTextValue": "MONOSPACE COMPACT"
},
"RegistrationDate": "2016-06-24",
"ImageUrl": "http://immatriculationapi.com/image.aspx/#UkVOQVVMVCBTQ8OJTklDIElJSQ==",
"ExtendedData": {
"anneeSortie": "2016",
"boiteDeVitesse": "",
"carburantVersion": "D",
"carrosserieVersion": "",
"classeSra": "",
"libVersion": "1.5 dCi 1461cm3 110cv ",
"libelleModele": "SCÉNIC III",
"marque": "RE",
"modele": "",
"produit": "",
"puissance": "5",
"version": "",
"cleCarrosserie": "",
"groupeSra": "",
"nbPlace": "5",
"datePremiereMiseCirculation": "24062016",
"questionBatterie": "",
"electrique": "",
"genre": "",
"typeVehicule": "",
"numSerieMoteur": "VF1JZ890H55864144",
"valeurANeufSRA": "",
"niveauRisqueVol": "",
"protectionConstructeur": "",
"puissanceDyn": "110",
"segmentVeh": "",
"KtypeId": "5853",
"EngineCC": "1461",
"Co2": "105",
"Cylinders": "4",
"CNIT": "M10RENVP472E768"
}
}
)
Step 2: I try to retrieve the values by making differents requests:
print_r($array->Description);
print_r($array->{'RegistrationDate'});
print_r($array->{'ExtendedData'}->{'puissance'});
print_r($array->ExtendedData->puissance);
// or :
echo $array->Description;
echo $array->ExtendedData->puissance;
echo $array->ExtendedData->libVersion;
I think there is a problem while encoding the Json, I have tried differents solutions but no success.
You only need to decode the JSON into a PHP data structure. Then you can access its properties
$xml = simplexml_load_string($my_xml);
$data = json_decode($xml->vehicleJson); // 👈 just decode the string
echo $data->Description;
echo $data->ExtendedData->puissance;
echo $data->ExtendedData->libVersion;
Demo ~ https://3v4l.org/ZjE9H
how to manage dynamic key in json
[
{
"batch_id": "132",
"benf_id": "ANP-JAI-1190",
"NA3": "",
"NA4": "",
"status": "Y",
"NA5": "",
"datapoint_id": "105",
"status_update_time": "28/8/2017 ",
"user_id": "santoshk",
"pop_id": "40",
"measuring": "1000ltr",
"weight": "100gm"
},
{
"batch_id": "133",
"benf_id": "ANP-JAI-1195",
"NA3": "",
"NA4": "",
"status": "Y",
"NA5": "",
"datapoint_id": "106",
"status_update_time": "28/8/2017 ",
"user_id": "santoshk",
"pop_id": "41",
"water": "1000ltr",
"medicine": "100gm"
}
]
// my php code
public function benf_status_update($jdata)
{
$count=0;
$this->load->model('m_sf_user');
while($count < count($jdata))
{
$batch_id = $jdata[$count]->batch_id;
$benf_id = $jdata[$count]->benf_id;
$m3=$jdata[$count]->NA3;
$m4=$jdata[$count]->NA4;
$status = $jdata[$count]->status;
$m5=$jdata[$count]->NA5;
$m1=$jdata[$count]->0;
$m2=$jdata[$count]->0;
$datapoint_id = $jdata[$count]->datapoint_id;
$status_update_time = $jdata[$count]->status_update_time;
$user_id =$jdata[$count]->user_id;
$pop_id = $jdata[$count]->pop_id;
$benf_id = substr($benf_id,8,strlen($benf_id));
$qry = "UPDATE pop_b_m_points a JOIN m_pop_batch b ON
b.pop_id=".$pop_id."
and b.batch_id=".$batch_id."
and a.data_p_id=b.dpoint_id
and a.benf_id=".$benf_id."
and a.m_point_id=".$datapoint_id."
SET a.status='".$status."',
a.m1='".$m1."',
a.m2='".$m2."',
a.m3='".$m3."',
a.m4='".$m4."',
a.m5='".$m5."' ,
a.update_time= (SELECT (DATE_FORMAT(STR_TO_DATE('".$status_update_time."', '%d/%m/%Y' ), '%Y%m%d')))";
$this->m_sf_user->jSONservices_u($qry);
$count++;
}
$x=array('json_status'=>"success");
echo json_encode($x);
}
You can simply use json_decode
json_decode($string) to convert String into Array/Object (stdClass).
Example:
$myRawJson = '{
"batch_id": "133",
"benf_id": "ANP-JAI-1195",
"NA3": "",
"NA4": "",
"status": "Y",
"NA5": "",
"datapoint_id": "106",
"status_update_time": "28/8/2017 ",
"user_id": "santoshk",
"pop_id": "41",
"water": "1000ltr",
"medicine": "100gm"
}';
$myAssoc = json_decode($myRawJson);
$myObject = (object)(json_decode($myRawJson));
var_dump($myAssoc['medicine']); //100gm
var_dump($myObject->medicine); //100gm
If you don't know for sure which columns you will get, but do want to save all. Then make an extra column 'data' in which you save the complete set of data through json_encode()
If you can make sure some fields are always there, use them in seperate columns in order to filter and order by those, but also use the data column to add the complete data set.
I was wondering how to extract only a certain part from a JSON String:
[
{
"ID": "132",
"countrycode": "DE",
"USERNAME": "CRC Titan2000",
"Nickname": "^7[6S] ^1Titan",
"Money": "550111",
"Distance": "105692714",
"Trip": "370839",
"Bonus": "223",
"Last Car": "RB4",
"Last Position": "The Hills",
"Server": "^7One"
},
{
"ID": "1634",
"countrycode": "ES",
"USERNAME": "lobocop",
"Nickname": "^4Leo ^1Messi",
"Money": "12816",
"Distance": "17091463",
"Trip": "25682",
"Bonus": "29",
"Last Car": "MRT",
"Last Position": "Bridge East",
"Server": "^7One"
},
{
"ID": "4240",
"countrycode": "GB",
"USERNAME": "Smacky",
"Nickname": "^7^d^6o^7^s",
"Money": "-532",
"Distance": "1987579",
"Trip": "7738",
"Bonus": "51",
"Last Car": "RB4",
"Last Position": "The Hills",
"Server": "^7One"
},
{
"ID": "5467",
"countrycode": "TR",
"USERNAME": "excaTR",
"Nickname": "^1Furkan^7Tr",
"Money": "7363",
"Distance": "17064283",
"Trip": "15747",
"Bonus": "31",
"Last Car": "RB4",
"Last Position": "Bridge East",
"Server": "^7One"
}
]
I only want to pull the "Last Position" of the "USERNAME" excaTR, but ignore all the others. Sort of like a MySQL query, where I want to echo the last position WHERE username='excaTR', but instead for PHP and JSON.
This is the code that I tried, but it didn't work
$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, true);
foreach ($stats_data as $_SESSION['username'] => $location){
echo $location['Last Position'];
}
You are not using foreach as it should be.
Have a look at your JSON, you have an array of objects.
So you have to iterate over you array, and check your object values.
By the way, in my answer, I use json_decode( ,false) to force result as a multidimensional array, matter of taste only.
$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, false);
foreach ($stats_data as $array) {
if ($array['USERNAME'] == 'excaTR') {
echo $array['Last Position'];
}
}
I have 2 records from 2 different query results. I have merged those data. but i have to display unique data depends on vName key.
Here is my result:
{
"val1": "9",
"vName": "abc",
"bname": "",
"cname": "",
"brid": "",
"cmpid": "154",
"logo": "",
"banner": "",
"description": "",
"catids": "",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "",
"compressthumb_logo": "",
"bigthumb_banner": "",
"compressthumb_banner": "",
"sp_ar": "Aperitif"
},
{
"val1": "9",
"vName": "abc",
"bname": "abc",
"cname": "abc",
"brid": "341",
"cmpid": "154",
"logo": "",
"banner": "6c497c72bfec4c694c1cc2c49066e7a1.png",
"description": "http:\/\/www.abc.com\/",
"catids": "9",
"sp_ar": "Aperitif",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "40cbcede9429cdb44895e0e6f4c050d2.png",
"compressthumb_logo": "40cbcede9429cdb44895e0e6f4c050d2.png",
"bigthumb_banner": "6c497c72bfec4c694c1cc2c49066e7a1.png",
"compressthumb_banner": "6c497c72bfec4c694c1cc2c49066e7a1.png"
}
Expected result should be only one of them, compare with vName:
{
"val1": "9",
"vName": "abc",
"bname": "",
"cname": "",
"brid": "",
"cmpid": "154",
"logo": "",
"banner": "",
"description": "",
"catids": "",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "",
"compressthumb_logo": "",
"bigthumb_banner": "",
"compressthumb_banner": "",
"sp_ar": "Aperitif"
}
How can i get the result?
Convert the data into an array where the key is your unique value.
You can do something like:
$data = array('this is your array of data');
$unique = array();
foreach($data as $value) {
if(!array_key_exists($value['vName'], $unique)) {
$unique[$value['vName']] = $value;
}
}
// $unique now contains only arrays with a unique 'vName', using the first it finds in the original list
$new_array = array_values($unique);
Assuming you have a array of associative array stored in $data, the following code will filter it based on vName and store array of associative arrays with unique vName in $filtered_data
$taken = array();
$filtered_data = array_filter($data, function($value) {
global $taken;
if (in_array($value['vName'], $taken)) {
return false;
}
else {
$taken[] = $value['vName'];
return true;
}
});
Here, the variable $taken keeps track of all the vName values that are currently in the $filtered_data. If you find a duplicate vName (that is currently there in $taken), it discards that element.
Try this, it should work for you.
$input = array_map("unserialize", array_unique(array_map("serialize",$input)));
I want create a json response with nested json object and group my actual results by id_hotel
MY ACTUAL JSON RESPONSE
{
"tag": "cities",
"success": 1,
"error": 0,
"items": 2,
"item": [
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": "Night",
"pos": "402",
"pes": "33",
"pis": "21",
"pus": "456"
},
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": "Day",
"pos": "0",
"pes": "1",
"pis": "0",
"pus": "1"
}
]
}
MY PHP CODE for the encoding response
$query = "SELECT * FROM cities WHERE city = 'London'";
$result = mysql_query($query) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["item"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["year"] = $row["year"];
$product["city"] = $row["city"];
$product["start"] = $row["start"];
$product["id_hotel"] = $row["id_hotel"];
$product["name"] = $row["name"];
$product["address"] = $row["address"];
$product["number_fr"] = $row["number_fr"];
$product["district"] = $row["district"];
$product["pr"] = $row["pr"];
$product["fres"] = $row["fres"];
$product["mode"] = $row["mode"];
$product["pos"] = $row["pos"];
$product["pes"] = $row["pes"];
$product["pis"] = $row["pis"];
$product["pus"] = $row["pus"];
// push single product into final response array
array_push($response["item"], $product);
}
// success
$response["items"] = mysql_num_rows($result);
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
What I desider
{
"tag": "cities",
"success": 1,
"error": 0,
"items": 2,
"item": [
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": [{
"value" : "Night",
"pos": "402",
"pes": "33",
"pis": "21",
"pus": "456"
},
{ "value" : "Day",
"pos": "0",
"pes": "1",
"pis": "0",
"pus": "1"
}]
}
]
}
thanks in advance for your attention!!
Add option JSON_FORCE_OBJECT in function. You can read about it in http://tr2.php.net/manual/en/json.constants.php .
json_encode($response, JSON_FORCE_OBJECT) ;
1st, I suggest you a small change to save you some lines, and thus, i add some code to achieve what you want
$query = "SELECT * FROM cities WHERE city = 'London'";
$result = mysql_query($query) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["item"] = array();
$current_id = NULL;
while ($row = mysql_fetch_array($result)) {
if ( $row->id_hotel !== $current_id ){
$response["item"][] = $row;
$response["item"]["mode"] = array();
}
$current_item = end($response["item"]);
$current_item["mode"][] = array("value"=>$row->value, "pes"=>$row->pes);
$current_id = $row->id_hotel;
}
// success
$response["items"] = mysql_num_rows($result);
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
Let me know if it works.
Note: Only used 1 variable for mode, for testing purposes, and didn´t unset the variables that I put into mode array, but should be enough to see if the main idea works. Feeling a bit lazy :P