I have a number of coordinates stored in a sqlite database. I need these coordinates to be used in a heatmap on leaflet.
I'm using the following plugin: https://github.com/Leaflet/Leaflet.heat
The data needs to be in the following format:
var addressPoints = [
[52.344161, 4.912279],
[52.342425, 4.913038],
[52.342034, 4.913256],
[52.341987, 4.912462]];
I extract the data from the sqlite database in PHP using:
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
while ($row = $results->fetchArray()) {
echo json_encode($row['coord']);
}
$db->close();
The data retrieved looks like:
"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"
How can I get the SQLite data inserted in 'var addressPoints' in a correct manner?
Thansk in advance,
JWB
If the data follows that same format with the quotes at start and end and double quotes in between pairs the following should produce an array with the pair as an entry.
$data='"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"';
$pairs=explode('""',trim($data,'"'));
print_r($pairs);
output:
Array
(
[0] => 52.344161000, 4.912279000
[1] => 52.342425000, 4.913038200
[2] => 52.342034000, 4.913256000
[3] => 52.341987000, 4.912462000
[4] => 52.342336000, 4.912106000
)
You could alter your initial php however which would produce different data
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
$json=array();
while( $row = $results->fetchArray() ) {
$json[]=$row['coord'];
}
$db->close();
$json=json_encode( $json );
echo $json;
if you needed this without the quotes around the values...
$json=str_replace('"','',$json);
in the javascript then you could do:
echo "var addressPoints={$json};";
Related
<?php
// header("Access-Control-Allow-Origin: *");
// header("Content-Type: application/json; charset=UTF-8");
require_once ('connection.php');
try {
$selectCatagory = 'select Catagory_id, Catagory_name, Catagory_image from district_shop.catagory';
$prepareCatagory = $conn -> prepare($selectCatagory);
$prepareCatagory ->execute(array());
while ($fetchCatagory = $prepareCatagory ->fetch(PDO::FETCH_ASSOC)) {
$Catagory = $fetchCatagory['Catagory_id'];
$selectSubCatagory = 'select * from district_shop.subcatagory where Catagory_id= :Cat_id';
$prepareSubCatagory = $conn -> prepare($selectSubCatagory);
$prepareSubCatagory -> execute(array(
'Cat_id' => $Catagory
));
while ($fetchSubCatagory = $prepareSubCatagory -> fetch(PDO::FETCH_ASSOC)) {
//print_r($fetchSubCatagory);
echo json_encode($fetchSubCatagory);
// It doesnot encoded to valid JSON
}
}
} catch (PDOException $th) {
$th-> errMessage();
}
?>
// The outpuut invalid JSON file is as :-
[{"Subcatogory_id":"1","Subcatagory_name":"Crasher Material","Subcatagory_description":"Crasher Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"2","Subcatagory_name":"Plumbing Items","Subcatagory_description":"Plumbing Items","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"3","Subcatagory_name":"Iron Material","Subcatagory_description":"Iron Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"4","Subcatagory_name":"Cementing","Subcatagory_description":"Cement Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"5","Subcatagory_name":"Marble & Tiles","Subcatagory_description":"Marble & Tiles","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"6","Subcatagory_name":"Electric Material","Subcatagory_description":"Electric Material","Active_Subcatagory":"Active","Catagory_id":"1"}][{"Subcatogory_id":"7","Subcatagory_name":"Sweets ","Subcatagory_description":"Sweets ","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"8","Subcatagory_name":"Salted(Namkeen)","Subcatagory_description":"Salted(Namkeen)","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"9","Subcatagory_name":"Cold and Beverages","Subcatagory_description":"Cold and Beverages","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"10","Subcatagory_name":"Food and Snacks","Subcatagory_description":"Food and Snacks","Active_Subcatagory":"Active","Catagory_id":"2"}]
Sir, I am unable to create its valid json as i have two tables in mySQL named catagory and subcatagory.
so nested while loop is used to extract subcatagory by using catagory. The output is encoded in json but it was no a valid JSON.
The problem is you're echoing multiple JSONs without nesting them properly. Instead of this:
[subcat1, subcat2, subcat3][subcat4, subcat5, subcat6] (invalid)
Your output should look like be one of these
[subcat1, subcat2, subcat3, subcat4, subcat5, subcat6] (valid flat array)
[[subcat1, subcat2, subcat3], [subcat4, subcat5, subcat6]] (valid nested arrays)
In your code, you should harvest responses into an array, which you echo json_encode() in the end.
...
$output = [];
while ($fetchCatagory ...) {
...
while ($fetchSubCatagory ...) {
// for nested array
$output[] = $fetchSubCatagory;
// for flat array
$output = array_merge($output, $fetchSubCatagory);
}
}
echo json_encode($output);
That should do the trick :-)
I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.
i have the problem to add elements to an json array.
The structure i want is that:
[{"method":"edit","type":"1", "template":"3", "meta":{"title":"Tools", "descirption":"Tools"}}]
The problem is that i add all these parameters dynamically.
So lets say i have for the start:
[{"method":"edit","type":"1", "template":"3"}]
How can i add the whole "meta" array and please do not be with push(), because than i will have another structure when i print it.
When i use
$json = json_decode($json, true);
I want to have:
array(
method' => edit,
'type' => 1,
'template' => 3,
'meta' => array('title' => '')
);
Thanks in advice !
So I'm going to assume you have the JSON to start with. So let's decode to PHP (as you noted correctly)
$json = json_decode($json, true);
So now we should have $json['method'], etc. Now let's define $meta
$meta = array('title' => '');
And add this to $json
$json['meta'] = $meta;
echo json_encode($json);
When your current JSON decodes in PHP using json_decode, it will decode into an array with one element, or array[0]. Therefore in order to access or any object you need to first point to that 0 index. Do it this way:
$json = '[{"method":"edit","type":"1", "template":"3"}]';
$arr = json_decode($json);
$arr[0]->meta = array('title' => '');
$json = json_encode($arr);
var_dump($json);
//Result:
// string '[{"method":"edit","type":"1","template":"3","meta":{"title":""}}]' (length=65)
When a user add the markers on the Google Map, I'm saving it as a JSON string on my MySQL database like this:
[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]
"k" is the latitude and "B" the longitude of the added marker.
I also save the polylines between the markers like this:
[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]
I have a function witch fetch all the markers and polylines from the database, to display it back to the screen, here is my query:
function getMarkersByTripId($tripId)
{
if ($bdd = mysqli_connect(_BDD_HOST_, _BDD_USERNAME_, _BDD_PASSWORD_, _BDD_NAME_)) {
$sql = 'SELECT DISTINCT `markers`, `polylines` FROM `trip` WHERE `trip_id` = "'.$tripId.'"';
$req = mysqli_query($bdd, $sql);
if ($req) {
while ($row = mysqli_fetch_row($req)) {
$jsonData= array('markers'=>$row[0], 'polylines'=>$row[1]);
}
echo json_encode($jsonData);
}
else {
echo json_encode(array('status' => 'failure'));
}
}
if ($bdd) {
mysqli_close($bdd);
}
}
a var_dump of $jsonData looks like this:
array(2) {
["markers"]=>
string(79) "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]"
["polylines"]=>
string(63) "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
}
In my JavaScript, when I'm doing:
console.log(jsonText);
It's formed like:
"{"markers":"[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]","polylines":"[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"}"
As you can see, it's a simple string containing the JSON result returned by the function getMarkerByTripId() function. Now, I want to convert my JSON string to an object like this:
var jsonData = JSON.parse(jsonText);
console.log(jsonData);
It seems working and it display something like:
Object { markers: "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]", polylines: "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]" }
The problem is: I can't access to the latitude/longitude (k/D JSON elements), it's always undefined, here is how I'm doing it after the JSON.parse(jsontext):
console.log(jsonData['markers'].k);
It always return "undefined" and in order to add the marker on the Google map, I need to know what I'm doing wrong with the JSON parsing. The rest is OK, I know how to loop through my JSON object to add the markers and the polylines on the map automatically.
I was thinking that when I'm fetching the JSON string from MySQL database, it may add double quote, witch can defect the JSON parsing. Thank you very much if someone can guide me to the right answer.
jsonData.markers is double json encoded you will first parse jsonData.markers key object
var jsonText = {
"markers": "[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]",
"polylines": "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
};
var markers = JSON.parse(jsonText.markers);
var polylines = JSON.parse(jsonText.polylines);
console.log('markers ', markers, ' polylines', polylines);
In php code: warp markers, polylines with json_decode() function in while loop, because both values are already json string, and when you use again json_encode these double encode.
while ($row = mysqli_fetch_row($req)) {
$jsonData= array(
'markers'=>json_decode($row[0]),
'polylines'=>json_decode($row[1])
);
}
UPDATE PHP CODE
<?php
$arr1 = array(
"markers" => '[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]',
"polylines" =>'[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]'
);
echo "//your problem \n";
echo json_encode($arr1);
$arr2 = array(
"markers" => json_decode('[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]'),
"polylines" =>json_decode('[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]')
);
echo "\n\n//my solution\n";
echo json_encode($arr2);
//after solution markers, polylines keys wrapped with one more array so you will need to use `[0]` index in javascript
// jsonText.markers[0].k; jsonText.markers[0].d etc
// you can also do
$arr3 = array(
"markers" => array_shift(json_decode('[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]')),
"polylines" =>array_shift(json_decode('[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]'))
);
echo "\n\n//another one more solution my solution\n";
echo json_encode($arr3);
//now you can access values in JavaScript
// jsonText.markers.k; jsonText.markers.d etc
?>
see more detail click here
The member 'markers' is an array, you must specify from which element you need the coordinates in this array.
Try this for accessing the first one to check if it works :
console.log(jsonData['markers'][0].k);
I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.