How to Parse the dynamic key vale in php - php

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.

Related

Impossible to fetch data from a json file into php variable

I'm using Giscloud's REST API to grab a json with some info that i need for my web app. The problem is that it seems impossible that I can fetch and/or decode any data from that json using the corresponding php functions. I think it has something to do with the way the json file is structured.
This is the json file (some fields edited):
{
"type": "maps",
"total": 3,
"page": 1,
"data": [
{
"id": "edited",
"name": "Mapa de Mantención en Linea",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563460,
"accessed": 1483563460,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "31",
"resource_id": "6102219",
"measure_unit": "meter",
"share": "f",
"bounds": " {\"xmin\":-8027875.3326789,\"xmax\":-7742459.4690621,\"ymin\":-4065685.5344885,\"ymax\":-3929474.7500843}"
},
{
"id": "edited",
"name": "Mapa de Operaciones",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563473,
"accessed": 1483563473,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "45",
"resource_id": "6102603",
"measure_unit": "meter",
"share": "f",
"bounds": "{\"xmin\":-8027263.8364526,\"xmax\":-7741847.9728358,\"ymin\":-4075469.474109,\"ymax\":-3939258.6897048}"
},
{
"id": "edited",
"name": "Mapa M&IC",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563449,
"accessed": 1483563449,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "35",
"resource_id": "6102604",
"measure_unit": "meter",
"share": "f",
"bounds": "{\"xmin\":-8028181.080792,\"xmax\":-7742765.2171752,\"ymin\":-4074552.2297696,\"ymax\":-3938341.4453654}"
}
]
}
These are the different ways that i've tried to decode this json and put it into a variable.
$json = curl_exec($ch);
// Number 1
$data = var_dump(json_decode($json));
echo $data['data'][0]['id'];
exit;
// Number 1 returns
object(stdClass)[21]
public 'code' => string 'FATAL' (length=5)
public 'msg' => string 'Internal error' (length=14)
// Number 2
$data = json_decode($json,true);
echo $data['data'][0]['id'];
// Number 2 returns
PHP Undefined index: data
I've tried several other similar functions, like print_r. Or change some values there and here, but nothing has worked.
I would appreciate a lot some help on this!
Some extra info:
There's no problem with curl. It executes correctly.
Yes, the server answers with a json file.
UPDATE
Using json_last_error() (no need of parameters) I was able to debbug. The function returns an int depending of the type of error. Mine was 0meaning that there's no error.
I think I ran out of ideas for this.
Loose the var_dump() thats just for debugging and it is stoppping the json_decode() from returning a PHP Object from the json_decode().
Then use the correct object syntax to address the object
$json = curl_exec($ch);
$data = json_decode($json);
// debug code
if ( json_last_error() > 0) {
echo json_last_error_msg();
} else
// this should print the data structure
print_r($data);
}
// end debug code
echo $data->data[0]->id;
If you want all the id's from all the occurances you can do
$json = curl_exec($ch);
$data = json_decode($json);
foreach ($data->data as $idx => $obj ){
echo "Occurance $idx = " . $obj->id;
}
Object syntax:
$json = curl_exec($ch);
$json_data = json_decode($json);
foreach ( $json_data->data as $data_item){
echo '<p>ID: ' . $data_item->id . ' -- Name: ' . $data_item->name . '</p>';
}
Array Syntax:
Get the data as an associated array by adding a second parameter TRUE to json_decode() php docs
$json = curl_exec($ch);
$data_array = json_decode($json, true);
foreach ( $data_array['data'] as $item){
echo '<p>ID: ' . $item['id'] . ' -- Name: ' . $item['name'] . '</p>';
}
i dont preferable to use cURL In this situation , you can use
file_get_contents
so here is a simple code
$userdata = json_decode(file_get_contents("JSON_URL_GOES_HERE"), true)
$u_ID = $userdata['data'][0]['id'];
and so on
see :file_get_contents

get unique data from multi-dimensional array list

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

How create a response json with nested objects in php?

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

pushed encoded json into another json

I'd encoded my result into json and I want to merge them. I wish to achieve this
[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
"img_src" [{img_src:1.jpg},{img_src:2.jpg}]
}
]
http://pastebin.com/7jKp9BUn
the result of each statement
[
{
"img_src": "1.jpg"
},
{
"img_src": "2.jpg"
}
]
the next one
[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
}
]
You can decode the JSON into arrays, append one to the other, then re-encode:
$s1 = '[
{
"img_src": "1.jpg"
},
{
"img_src": "2.jpg"
}
]';
$s2 = '[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
}
]';
//decode each
$arr1 = json_decode($s1, true);
$arr2 = json_decode($s2, true);
$arr2[0]['img_src'] = $arr1;
//re-encode as a JSON string and show output
$sf = json_encode($arr2);
echo $sf;
This should give the result you described, with "img_src"... as a sub-array of the larger set.
Looking at your php code you could do it this way as well in one shot.
$stmt = $db->prepare("
SELECT post_id,content,date,category_id,lp_title,lp_image,lp_canonicalUrl,lp_url,lp_desc,lp_iframe,lp_iframe_id
FROM post_items inner JOIN user ON post_items.user_id = user.user_id
WHERE post_items.user_id = ? order by post_items.post_id desc LIMIT ?,?");
$stmt->bind_param('iii', $userid, $itemStart, $itemEnd);
$stmt2 = $db->prepare("SELECT photo_upload.img_src FROM photo_upload inner JOIN post_items ON post_items.photo_set_id = photo_upload.photo_set_id
WHERE post_items.photo_set_id = photo_upload.photo_set_id ");
//store the images in a separate array
$imgArray = array();
if ($stmt2->execute()) {
$photo_items = $stmt2->get_result();
while ($obj2 = $photo_items->fetch_object()) {
$imgArray[] = $obj2;
}
}
if($stmt->execute()){
$post_items = $stmt->get_result();
if(mysqli_num_rows($post_items) > 0){
while ($obj = $post_items->fetch_object()) {
$jsonData[] = $obj;
// check if there are any elements in the array
if(count($imgArray) > 0){
// set the img_src index of the jsonData array with the elements of the other array
$jsonData['img_src'] = $imgArray;
}
}
$i = json_encode($jsonData);
echo $i;
}
}

How can I edit my json to not include the row numbers

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

Categories