JSON from PHP – nested arrays - php

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

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

PHP to GEOJSON array not looping rows in MYSQL database

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.

Getting JSON data from API as array or object

I am using sports-radar API to get the schedule of NFL week 1. The API returns the following data in json format (I shortened string for example).
"id": "8e45fe2d-fb95-4504-845d-7c815623ccd6",
"year": 2018,
"type": "REG",
"name": "REG",
"week": {
"id": "37435167-5cf6-4cce-b405-ff0e264ced9c",
"sequence": 1,
"title": "1",
"games": [{
"id": "0822b924-eadc-4398-bfe6-83cbbf3a2912",
"status": "scheduled",
"reference": "57570",
"number": 4,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "6ed18563-53e0-46c2-a91d-12d73a16456d",
"name": "Lucas Oil Stadium",
"city": "Indianapolis",
"state": "IN",
"country": "USA",
"zip": "46225",
"address": "500 South Capitol Avenue",
"capacity": 67000,
"surface": "artificial",
"roof_type": "retractable_dome"
},
"home": {
"id": "82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9",
"name": "Indianapolis Colts",
"alias": "IND",
"game_number": 1
},
"away": {
"id": "ad4ae08f-d808-42d5-a1e6-e9bc4e34d123",
"name": "Cincinnati Bengals",
"alias": "CIN",
"game_number": 1
},
"broadcast": {
"network": "CBS"
}
}, {
"id": "0a456149-c547-4856-9b1b-86e1d93887ae",
"status": "scheduled",
"reference": "57574",
"number": 8,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "3c85d89a-ec66-4983-acd5-1381d6c8673a",
"name": "Mercedes-Benz Superdome",
"city": "New Orleans",
"state": "LA",
"country": "USA",
"zip": "70112",
"address": "1500 Sugar Bowl Drive",
"capacity": 73208,
"surface": "artificial",
"roof_type": "dome"
},
"home": {
"id": "0d855753-ea21-4953-89f9-0e20aff9eb73",
"name": "New Orleans Saints",
"alias": "NO",
"game_number": 1
},
"away": {
"id": "4254d319-1bc7-4f81-b4ab-b5e6f3402b69",
"name": "Tampa Bay Buccaneers",
"alias": "TB",
"game_number": 1
},
"broadcast": {
"network": "FOX"
I used the following website as a tutorial on how to display only the the data I need and how to loop over it
Note the JSON string is stored in the variable $schedule
MY Code
// JSON string
$jsonData = $schedule; //get json string
// Convert JSON string to Array
$jsonArray = json_decode($jsonData, true);
// Convert JSON string to Object
$jsonObject = json_decode($schedule);
Looping through PHP Array or Object
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"] . ", " . $value["away"] . "<br>";
}
// Loop through Object
$someObject = jsonObject
foreach($someObject as $key => $value) {
echo $value->home . ", " . $value->away . "<br>";
}
My ERRORS
When trying to convert the string to an array and attempting to get the away team name I get the error Illegal string offset 'away' same problem with home and all other data
When trying to access data as an object I get the following error Trying to get property of non-object
I followed the tutorial to the letter. Yet im getting the basic errors above...? Any help and explanation would be appreciated. Thank you
EDIT:
var_export($schedule) returns the following:
array ( 'id' => '8e45fe2d-fb95-4504-845d-7c815623ccd6', 'year' => 2018, 'type' => 'REG', 'name' => 'REG', 'week' => array ( 'id' => '37435167-5cf6-4cce-b405-ff0e264ced9c', 'sequence' => 1, 'title' => '1', 'games' => array ( 0 => array ( 'id' => '0822b924-eadc-4398-bfe6-83cbbf3a2912', 'status' => 'scheduled', 'reference' => '57570', 'number' => 4, 'scheduled' => '2018-09-09T17:00:00+00:00', 'entry_mode' => 'INGEST', 'venue' => array ( 'id' => '6ed18563-53e0-46c2-a91d-12d73a16456d', 'name' => 'Lucas Oil Stadium', 'city' => 'Indianapolis', 'state' => 'IN', 'country' => 'USA', 'zip' => '46225', 'address' => '500 South Capitol Avenue', 'capacity' => 67000, 'surface' => 'artificial', 'roof_type' => 'retractable_dome', ), 'home' => array ( 'id' => '82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9', 'name' => 'Indianapolis Colts', 'alias' => 'IND', 'game_number' => 1, ),
You are dealing with array of arrays. Try something like this:
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"]["name"] . ", " . $value["away"]["name"] . "<br>";
}

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

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

Categories