Reformatting Json to geoJson in PHP (Laravel) - php

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

Related

PHP Array and Updating an Array with data from another nested array [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How can I replace a specific key's value in an array in php?
(2 answers)
Closed 7 months ago.
I all, I've been staring at this for hours so any help is greatly appreciated. I have an array...
$aircraft = [
'N7826C' => ['nnum' => 'N7826C', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N226PD' => ['nnum' => 'N226PD', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N326PD' => ['nnum' => 'N326PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N826PD' => ['nnum' => 'N826PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0']
];
With that array, I implode it to get a list of the nnums to pass through a API....
$aircraftNNUMlist = implode(',', array_map(function($v) { return $v['nnum']; }, $aircraft));
$json = file_get_contents('https://airlabs.co/api/v9/flights?_fields=reg_number,lat,lng&reg_number='.$aircraftNNUMlist.'&api_key=XXXXX');
That API returns...
{
"request": {
"lang": "en",
"currency": "USD",
"time": 15,
"id": "c9by9lmq1q0",
"server": "z",
"host": "airlabs.co",
"pid": 322387,
"key": {
"id": 19146,
"api_key": "xxxxxxxxxxxxxxxx",
"type": "free",
"expired": "2022-08-20T22:00:00.000Z",
"registered": "2022-07-19T03:51:04.000Z",
"limits_by_hour": 2500,
"limits_by_minute": 250,
"limits_by_month": 1000,
"limits_total": 628
},
"params": {
"_fields": "reg_number,lat,lng",
"reg_number": "N60NT,N40NT,N30NT,N10NT",
"lang": "en"
},
"version": 9,
"method": "flights",
"client": {
"ip": "xxxxxxxxxxxxxxxxx",
"geo": {
"country_code": "US",
"country": "United States",
"continent": "North America",
"city": "Provo",
"lat": 40.2181,
"lng": -111.6133,
"timezone": "America/Denver"
},
"connection": {
"type": "corporate",
"isp_code": 46606,
"isp_name": "Unified Layer"
},
"device": {},
"agent": {},
"karma": {
"is_blocked": false,
"is_crawler": false,
"is_bot": false,
"is_friend": false,
"is_regular": true
}
}
},
"response": [
{
"reg_number": "N60NT",
"lat": 34.11,
"lng": -117.69
}
],
"terms": "Unauthorized access is prohibited and punishable by law. \nReselling data 'As Is' without AirLabs.Co permission is strictly prohibited. \nFull terms on https://airlabs.co/. \nContact us info#airlabs.co"
}
I am having trouble looping through the "response" of the API return (stored at $json) to update the corresponding index in $aircraft. If a nnum isn't currently active there will not be a entry in "response" for instance "response" only has N60NT in the return array. I am fairly new to arrays so I've been taking swings in the dark and nothing seems to be right.
I presume you have json_decoded your api json response into a PHP array. Well actually:
$arr = json_decode($json_form_api, true);
$response = $arr["response"];
foreach ($response as $sub) {
$reg = $sub["reg_number"];
$aircraft[$reg]["lat"] = $sub["lat"];
$aircraft[$reg]["lng"] = $sub["lng"];
}

Printing a foreach loop in a loop maintaining json

I have this code as I am trying to implement a json code using foreach loop
foreach ($single_google as $row) {
$data['step'][] = array(
"#type" => "HowToStep",
"url" => "https://example.com/kitchen#step1",
"name" => "Prepare the surfaces",
"itemListElement" => array(),
"image" => [
"#type" => "ImageObject",
"url" => "https://example.com/photos/1x1/photo-step1.jpg",
"height" => "406",
"width" => "305"
],
);
$all_step_google = json_decode($row["steps"]);
foreach ($all_step_google as $single_step_google) {
$data['itemListElement'][] = array(
"#type" => "HowToDirection",
"text" => "testing",
);
}
}
print_r(json_encode($data));
at the end of the coding, trying to run it I got this
{
"#type": "HowToStep",
"url": "https://example.com/kitchen#step1",
"name": "Prepare the surfaces",
"itemListElement": [],
"image": {
"#type": "ImageObject",
"url": "https://example.com/photos/1x1/photo-step1.jpg",
"height": "406",
"width": "305"
}
}
],
"itemListElement": [
{
"#type": "HowToDirection",
"text": "test."
}
instead of this which I needed actually.
{
"#type": "HowToStep",
"url": "https://example.com/kitchen#step1",
"name": "Prepare the surfaces",
"itemListElement": [
{
"#type": "HowToDirection",
"text": "Test"
}
],
"image": {
"#type": "ImageObject",
"url": "https://example.com/photos/1x1/photo-step1.jpg",
"height": "406",
"width": "305"
}
}
],
I want the "itemListElement" => array(), to print before the "image" => [] but it kept printing after the foreach loop. Please help me, am getting lost.
You use $data['itemListElement'][] = array(... on your second loop so that will assign new key to your data master array instead, the right code should be like this
............
foreach ($all_step_google as $key => $single_step_google) {
$data['step'][$key]['itemListElement'][] = array(
"#type" => "HowToDirection",
"text" => "testing",
);
}
............

Include variable into array if not empty inside foreach

Include the name variable if the value is not empty inside the foreach. I tried this method code below but it include outside the array. I want to include within the array.
Sample Code:
$load_array = array();
foreach($stmt->fetchAll() as $row){
$load_array[] = array(
'name' => $row['name'],
'start_location' => array(
'address' => $row['start_address'],
'coords' => array (
'lat' => floatval($row['start_lat']),
'lng' => floatval($row['start_lng']),
),
),
);
if(!empty($row['shift_start'])) { $load_array['shift_start'] = $row['shift_start'];}
if(!empty($row['shift_end'])) { $load_array['shift_end'] = $row['shift_end'];}
}
return json_encode($load_array);
Output code above:
{
"0": {
"name": "Ramon Macger",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
}
},
"1": {
"name": "Roberto",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
}
},
"shift_start": "14:00",
"shift_end": "17:00"
}
The output should be like this:
{
"0": {
"name": "Ramon Macger",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
},
"shift_start": "14:00",
"shift_end": "17:00"
},
"1": {
"name": "Roberto",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
},
"shift_start": "14:00",
"shift_end": "17:00"
},
}
The shift_start and shift_end should be within the array not outside. My code is working in 1 array only and not on the foreach. However, it doesn't working within for each.
You need to add shift_start and shift_end values into the data array before you push it into $load_array. Something like this:
foreach($stmt->fetchAll() as $row){
$data = array(
'name' => $row['name'],
'start_location' => array(
'address' => $row['start_address'],
'coords' => array (
'lat' => floatval($row['start_lat']),
'lng' => floatval($row['start_lng']),
),
),
);
if(!empty($row['shift_start'])) {
$data['shift_start'] = $row['shift_start'];
}
if(!empty($row['shift_end'])) {
$data['shift_end'] = $row['shift_end'];
}
$load_array[] = $data;
}

Add array elements in an array position

How can I add an array to array position:
Something like a:
<?php
$newArr = array('email' => array("id" => "5678", "token" => "fghjk"));
$arr = array(
"auth"=>
array(
'users'=>
array(
'id' =>"456yhjoiu",
'token' => "asdfghjkrtyui678"
)
)
);
somefunction($arr['auth'], $newArr);
I've tried array_push() but it added zero (0) before 'email' instead.~
I'm doing this to get a json output, something like this:
}
"auth": {
"users": {
"id": "456yhjoiu",
"token": "asdfghjkrtyui678"
},
"email": {
"id": "5678",
"token": "fghjk"
}
}
}
but I have this output:
{
"auth": {
"users": {
"id": "456yhjoiu",
"token": "asdfghjkrtyui678"
},
"0": {
"email": {
"id": "5678",
"token": "fghjk"
}
}
}
$data = ['auth' => array_merge($arr['auth'], $newArr)];
or old array notation <= PHP5.3
$data = array('auth' => array_merge($arr['auth'], $newArr));

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

Categories