PHP to GEOJSON array not looping rows in MYSQL database - php

My PHP file connects successfully to a MSQL database and queries all the columns in 3 tables.
$sql = "SELECT * FROM facilitator, address, certification WHERE certification.ID=10002 LIMIT 0,3";
I'm limiting the output to 3 rows for this example.
But my array is producing multiple sets of the same user's data. It appears not to be looping through the database's rows. Here's the PHP array
// Create array
$geojson = array('type' => 'FeatureCollection', 'features' => array());
// Loop each row in database
while($row = mysqli_fetch_assoc($result)) {
$marker = array(
'type' => 'Feature',
'properties' => array(
'Name' => $row['First_Name'],
),
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row["Longitude"], $row["Latitude"]
)
)
);
array_push($geojson['features'], $marker);
}
$json_string = json_encode($geojson, JSON_PRETTY_PRINT);
echo "<pre>".$json_string."<pre/>";
And the GEOJSON results (limited to 3 users)
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"Name": "Luz"
},
"geometry": {
"type": "Point",
"coordinates": [
"175.298090",
"-37.791458"
]
}
},
{
"type": "Feature",
"properties": {
"Name": "Luz"
},
"geometry": {
"type": "Point",
"coordinates": [
"175.298090",
"-37.791458"
]
}
},
{
"type": "Feature",
"properties": {
"Name": "Luz"
},
"geometry": {
"type": "Point",
"coordinates": [
"175.298090",
"-37.791458"
]
}
}
]
}
You can see "Luz" data is repeated each time. Can you help me with where the array is incorrect please? Thank you.

Okay. So, the array is working correctly, but preceded by an incorrect SQL statement requiring suitable JOIN. Something like this provides a working combination,
SELECT First_Name, Last_Name, Name
FROM facilitator
INNER JOIN certification USING (Client_ID)
WHERE facilitator.Last_Name='Smith'
I should point out that the JSON file coordinates are wrapped in quotes " which produces a string and not a number required for maps.

Related

How to have multiple live real time data markers from a php file in mapbox?

This is the code from my php that updates real live data in my mapbox:
$value = array(
"geometry"=>array(
"type"=> "Point",
"coordinates"=> [floatval($longitude),floatval($lat)]
) ,
"type"=>"Feature",
"properties" => array(
"description" => "<strong>Visitor No.1</strong>"
)
);
// Use json_encode() function
$json = json_encode($value);
// Display the output
echo($json);
Pretty print of json data:
{
"geometry":{
"type":"Point",
"coordinates":[
120.92718138599082,
14.313414704855333
]
},
"type":"Feature",
"properties":{
"description":"Visitor No.1<\/strong>"
}
}
Right now it only gives out 1 live map marker in my mapbox map. Here's a snip of code from my mapbox php file that gets the data from this json_encode file:
var url = 'ayyyy.php'; //name of php file that i get the live data from
map.on('load', function() {
window.setInterval(function() {
map.getSource('points').setData(url);
}, 2000);
map.addImage('pulsing-dot', pulsingDot, { pixelRatio: 1.3 });
map.addSource('points', {
'type': 'geojson',
'data': url
});
Right now I want to try a json print like this: (but i don't know how)
{
"geometry":{
"type":"Point",
"coordinates":[
120.92718138599082,
14.313414704855333
]
},
"type":"Feature",
"properties":{
"description":"Visitor No.1<\/strong>"
},
"geometry":{
"type":"Point",
"coordinates":[
0,
0
]
},
"type":"Feature",
"properties":{
"description":"Visitor No.1<\/strong>"
}
}
I tried doing this:
$value = array(
"geometry"=>array(
"type"=> "Point",
"coordinates"=> [floatval($longitude),floatval($lat)]
) ,
"type"=>"Feature",
"properties" => array(
"description" => "<strong>Visitor No.1</strong>"
),
$value = array(
"geometry"=>array(
"type"=> "Point",
"coordinates"=> [floatval($longitude),floatval($lat)]
) ,
"type"=>"Feature",
"properties" => array(
"description" => "<strong>Visitor No.1</strong>"
)
);
But it didn't work. Any ideas? Thanks in advance!
Thanks for the other comentator for pointing the value thing! Realized i had to do this type of pretty print for multiple markers.
{
'type': 'FeatureCollection',
'features': [
{
"geometry": {
"type": "Point",
"coordinates": [
-131.21888112093228,
-26.526198945019374
]
},
"type": "Feature",
"properties": {}
},
{
"geometry": {
"type": "Point",
"coordinates": [
0,
0
]
},
"type": "Feature",
"properties": {}
}
]
}
had to add feature collection part. Thank you
https://3v4l.org/vfAHd
here's the json_encode if anyone's wondering.

JSON from PHP – nested arrays

I'm outputting some JSON from PHP, but I'm having difficulty understanding how to do nested arrays (at least I think that is what it is called)
I can output single sets, for example, "type": "Feature" but how would I do
"geometry": {
"type": "Point",
"coordinates": [-77.03238901390978,38.913188059745586]
},
For example, the desired output for one item in the JSON array might be:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-77.03238901390978,38.913188059745586]
},
"properties": {
"title": "Mapbox DC",
"description": "1714 14th St NW, Washington DC",
"marker-color": "#fc4353",
"marker-size": "large",
"marker-symbol": "monument"
}
},
And my code so far looks like this:
<?php
$projects = $pages->find('template=project-detail, sort=sort');
$projects_array = array();
foreach ($projects as $project) {
$title = $project->title;
$long = $project->project_location_marker_long;
$lat = $project->project_location_marker_lat;
$projects_array[] = array(
'title' => $title
);
}
$projects_json = json_encode($projects_array, true);
?>
<script>
var geojson = <?php echo echo $projects_json; ?>
</script>
Which generates something like the following:
[{
"title": "Steel Strike 1980"
}, {
"title": "Chapel Flat Dyke Boat"
}]
A nested array is simple to create. Here is one example:
$my_array = array(
'string_example' => 'asdf',
'integer_example' => 42,
'array_example' => array() // this array is nested
);
Inside this nested array, you could put anything you'd like. For instance, let's put the exact same thing in it:
$my_array = array(
'string_example' => 'asdf',
'integer_example' => 42,
'array_example' => array(
'string_example' => 'asdf',
'integer_example' => 42,
'array_example' => array()
)
);
So working from your code example, here is a start, given the data you included:
foreach ($projects as $project) {
$title = $project->title;
$long = $project->project_location_marker_long;
$lat = $project->project_location_marker_lat;
$projects_array[] = array(
'geometry' => array(
'coordinates' => array($long, $lat)
)
'properties' => array(
'title' => $title
)
);
}
This will result in the following json when encoded:
{
"geometry": {
"coordinates": [-77.03238901390978,38.913188059745586]
},
"properties": {
"title": "Mapbox DC",
}
}
There's a simple way to figure this out. Just take your example JSON, decode it and see what the output looks like:
<?php
$json = '
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-77.03238901390978,38.913188059745586]
},
"properties": {
"title": "Mapbox DC",
"description": "1714 14th St NW, Washington DC",
"marker-color": "#fc4353",
"marker-size": "large",
"marker-symbol": "monument"
}
}';
var_export(json_decode($json, true));
Output:
array (
'type' => 'Feature',
'geometry' =>
array (
'type' => 'Point',
'coordinates' =>
array (
0 => -77.032389013909778,
1 => 38.913188059745586,
),
),
'properties' =>
array (
'title' => 'Mapbox DC',
'description' => '1714 14th St NW, Washington DC',
'marker-color' => '#fc4353',
'marker-size' => 'large',
'marker-symbol' => 'monument',
),
)
if you like to encode for example the lat/lon of your sample code it would be:
$title = $project->title;
$long = $project->project_location_marker_long;
$lat = $project->project_location_marker_lat;
$projects_array[] = array(
'title' => $title,
'coordinates' => array($lat,$lon)
);
this will result in something like this:
[{
"title": "Steel Strike 1980",
"coordinates": [-77.03238901390978,38.913188059745586]
}, {
"title": "Chapel Flat Dyke Boat",
"coordinates": [-77.03238901390978,38.913188059745586]
}]

Elasticsearch Snowball Analyzer wants exact word

I Have been using Elastic Search for a project, but I find the result of Snowball Analyzer a bit strange.
Below is my example of Mapping used.
$myTypeMapping = array(
'_source' => array(
'enabled' => true
),
'properties' => array(
'id' => array(
'type' => 'integer',
'index' => 'not_analyzed'
),
'name' => array(
'type' => 'string',
'analyzer' => 'snowball',
'boost' => 2.0
),
'food_types' => array(
'type' => 'string',
'analyzer' => 'keyword'
),
'location' => array(
'type' => 'geo_point',
"geohash_precision"=> 4
),
'city' => array(
'type' => 'string',
'analyzer' => 'keyword'
)
)
);
$indexParams['body']['mappings']['online_pizza'] = $myTypeMapping;
// Create the index
$elastic_client->indices()->create($indexParams);
On quering the http://localhost:9200/online_pizza/online_pizza/_mapping I get the following results,
{
"online_pizza": {
"properties": {
"city": {
"type": "string",
"analyzer": "keyword"
},
"food_types": {
"type": "string",
"analyzer": "keyword"
},
"id": {
"type": "integer"
},
"location": {
"type": "geo_point",
"geohash_precision": 4
},
"name": {
"type": "string",
"boost": 2,
"analyzer": "snowball"
}
}
}
}
My Question is, I have data, which has Name field as "Milano". On querying for "Milano" I get the desired result, but if I query for "Milan" or "Mil" I get no result found.
{
"query": {
"query_string": {
"default_field": "name",
"query": "Milan"
}
}
}
I've also tried to snowball analyzer during querying, no help.
{
"query": {
"query_string": {
"default_field": "name",
"query": "Milan",
"analyzer": "snowball"
}
}
}
Second Question is Keyword Search is case sensitive, eg, Pizza != pizza, how do i get away with this ?
Thanks,
The snowball stemmer doesn't want exact words. If you try it with jumping, it outputs jump as expected.
However, depending on the case, you word may be understemmed as it doesn't match any stemmer rule.
If you use the analyze API endpoint (more info here), you will see that analyzing Milano with snowball analyzer gives you the token milano :
GET _analyze?analyzer=snowball&text=Milano
Output :
{
"tokens": [
{
"token": "milano",
"start_offset": 0,
"end_offset": 6,
"type": "<ALPHANUM>",
"position": 1
}
]
}
Then, using same snowball analyzer on Mil like this :
GET _analyze?analyzer=snowball&text=Mil
gives you this token :
{
"tokens": [
{
"token": "mil",
"start_offset": 0,
"end_offset": 3,
"type": "<ALPHANUM>",
"position": 1
}
]
}
That's why searching for 'milan' or 'mil' won't match 'Milano' documents : it doesn't match the milano term stored in index.
For your second question, you can prepare a custom analyzer combining keyword tokenizer and a lowercase tokenfilter in order to have your keyword search case-insensitive (if you use the same analyzer at search time) :
POST index_name
{
"analysis": {
"analyzer": {
"case_insensitive_keyword": {
"type": "custom",
"tokenizer": "keyword",
"filter": ["lowercase"]
}
}
}
}
Test :
GET analyse/_analyze?analyzer=case_insensitive_keyword&text=Choo Choo
Output :
{
"tokens": [
{
"token": "choo choo",
"start_offset": 0,
"end_offset": 9,
"type": "word",
"position": 1
}
]
}
I hope I'm clear enough in my explainations :)

Reformatting Json to geoJson in PHP (Laravel)

I have laravel outputting the following:
[
{
"id": 3,
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"id": 4,
"lat": "44.8",
"lon": "1.7"
},
{
"id": 22,
"lat": "37.59046",
"lon": "-122.348994"
}
]
i would like it to be the geoJson format:
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [lat, lon]},
"properties": {
"name": "value"
}
}
]
}
I know i need some sort of loop. But i'm not sure how to structure it in PHP. Any guidance would be greatly appreciated. Trying to build a map application that could have several thousand markers on a world view. I'm already thinking about clustering, but need to get past this basic step.
Thanks!
I modified the loop, the arrangement was a bit off. And turned it into a function if anyone is interested:
function geoJson ($locales)
{
$original_data = json_decode($locales, true);
$features = array();
foreach($original_data as $key => $value) {
$features[] = array(
'type' => 'Feature',
'geometry' => array('type' => 'Point', 'coordinates' => array((float)$value['lat'],(float)$value['lon'])),
'properties' => array('name' => $value['name'], 'id' => $value['id']),
);
};
$allfeatures = array('type' => 'FeatureCollection', 'features' => $features);
return json_encode($allfeatures, JSON_PRETTY_PRINT);
}
Just use json_decode() on the original values and rebuild/reconstruct a new one. Consider this example:
$original_json_string = '[{"id": 3,"lat": "38.8978378","lon": "-77.0365123"},{"id": 4,"lat": "44.8","lon": "1.7"},{"id": 22,"lat": "37.59046","lon": "-122.348994"}]';
$original_data = json_decode($original_json_string, true);
$coordinates = array();
foreach($original_data as $key => $value) {
$coordinates[] = array('lat' => $value['lat'], 'lon' => $value['lon']);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => array(
'type' => 'Feature',
'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
'properties' => array('name' => 'value'),
),
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);
$final_data should yield something like:
{
"type": "FeatureCollection",
"features": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
{
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"lat": "44.8",
"lon": "1.7"
},
{
"lat": "37.59046",
"lon": "-122.348994"
}
]
},
"properties": {
"name": "value"
}
}
}

Creating a PHP object with out the use of a key?

I've got a request to present the data in the following format as a JSON feed:
{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
However in my PHP code, I think I need to have a key itterator - but I end up with this format:
{
"0": {
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
"1": {
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
}
Any ideas on how to build the first data set with out having the index iterator?
simple create an array of objects, no need for the key (notice the [ ] surrounding your list)
json.txt
[{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}]
example.php
<?php
$data = json_decode(file_get_contents('./json.txt'));
?>
It can be built like this:
$arr = array(
array(
'id' => 123,
'info' => array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL'
)
),
array(
'id' => 456,
'info' => array(
'code' => 'ZDN',
'description' => 'test2',
'type' => 'CLR'
)
)
);
echo json_encode($arr);
Outputs
[
{
"id": 123,
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL"
}
},
{
"id": 456,
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR"
}
}
]
the JSON format you've specified in the first example (ie the requested format) is not valid JSON.
A valid JSON string must evaluate to a single Javascript object; the example you've given evaluates to two Javascript objects, separated by a comma. In order to make it valid, you would need to either enclose the whole thing in square brackets, to turn it into a JS array or enclose it in curly braces, and give each of the two objects a key.
The PHP code you've written is doing the second of these two options. It is therefore generating valid JSON code, about as close to the original request as could be expected while still being valid.
It would help if you'd shown us the PHP code that you've used to do this; without that, I can't really give you advice on how to improve it, but if you want to switch to the square bracket notation, all you need is to put your PHP objects into an unkeyed array, and json_encode() should do it all for you; you shouldn't need to use a keyed array or an iterator for that.
The only reason json_encode should produce the output you're seeing is adding another named key to the array that you're passing to json_encode, by default it should work as you want:
$json = '[
{
"id": "123",
"recall_info": {
"code":"ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "123",
"recall_info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
]';
$php = array(
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL',
'date' => '09/08/2012'
)
),
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test2',
'type' => 'CLR',
'date' => '16/02/2012'
)
)
);
var_dump(json_encode($php));

Categories