Trying to use PHP to format data for the geometry part of GeoJSON (Polygon)
$sql = "SELECT ST_AsGeoJSON(`geom`) as Geo FROM `usa` WHERE 1";
Returns records that look like:
{"type": "Polygon", "coordinates": [[[-101.4073933...
My code so far, I tried formatting the geometry block 3 different ways, all failed.:
while ($res = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$msg [] = array(
'type' => 'Feature',
'geometry' =>
$res['Geo'],
/// ERROR "geometry" member should be object, but is an String instead
//"geometry":"{\"type\": \"Polygon\", \"coordinates\": [[[-104.05361517875079, 41.698
'geometry' => array(
$res['Geo'],
), ///ERROR "geometry" member should be object, but is an Array instead
//"geometry":["{\"type\": \"Polygon\", \"coordinates\": [[[-104.05361517875079, 41.6
'geometry' => array(
'type' => $res['Geo'].['type'],
'coordinates' => $res['Geo'].['coordinates'],
),
//"geometry":{"type":"{\"type\": \"Polygon\", \"coordinates\": [[[[-122.4020155875262, 48.22521
It should end up looking something like this:
"geometry": { "type": "Polygon", "coordinates": [[[ -73.3450469
ST_AsGeoJSON returns, as the name suggests, JSON. That means $res['Geo'] is a string, a JSON string, representing a GeoJSON object. If you put that string into a PHP array which you later json_encode, you're producing the JSON encoding of a string. What you want instead is an array or object, which you can then json_encode and which will be an object in JSON, not a string.
So, JSON-decode the value you get from the database to get a PHP object:
$msg[] = array(
'type' => 'Feature',
'geometry' => json_decode($res['Geo']),
...
);
When JSON-encoding $msg later, it'll look like:
"geometry": {"type": "Polygon", "coordinates": ...}
Related
I know this has been asked before, however nothing seems to work
I have following json output:
"coordinates": [
"18.366466",
"29.898110"
]
However, the output I want is:
"coordinates": [
18.366466,
29.898110
]
$coordinates = array($result->lat, $result->lng);
$output[$i++] = array(
"type" => "Feature",
"geometry" => array("type" => "Point",
"coordinates" => $coordinates),
"properties" => array(
"ID" => $result->id,
"icon" => $result->icon,
"tags" => $tagsForJson,
"title" => $result->title,
"description" => $result->description));
Trim, str_replace and all of those functions are not working
Thank you!
What you're looking to do is type-cast this data into an float.
After preparing (trimming, etc) the string with the numbers, you can do something like this:
$coordinates = array((float)$result->lat, (float)$result->lng);
Or to cast the whole array at once, more simply you could utilize array_map and floatval
$coordinates = array_map('floatval', $coordinates);
I want to modify a value inside JSON. Let's say I have this example JSON and I want to have the php change the phone number:
$data = '{
"firstName": "John",
"lastName": "Smith",
"age": 27,
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
}
]
}'
It sounds like I have to convert to an array using json decode:
$data = json_decode($data,true);
Which gives me this:
array (
'firstName' => 'John',
'lastName' => 'Smith',
'age' => 27,
'phoneNumbers' =>
array (
0 =>
array (
'type' => 'home',
'number' => '212 555-1234',
),
),
)
How do I then insert my own variable value into the array please? From my googling it looks like I might be on the right path with something along these lines:
$number = '50';
$data[$key]['age'] = $number;
What it does though, is just add it onto the end of the array, instead of correcting the value in place of the array file.
Firstly, you need to convert your json to PHP array usign json_decode function. check below code for updating/inserting keys:
$data['age'] = $number; // to update age
$data['newkey'] = 'newvalue'; //it will add key as sibling of firstname, last name and further
$data['phoneNumbers'][0]['number'] = '222 5555 4444'; //it will change value from 212 555-1234 to 222 5555 4444.
You just need to consider array format. If key exists then you can update value else it will be new key in array. Hope it helps you.
I am working with Acuity Scheduling API and in order to post a custom field, I need to have a JSON object inside of the array that has 2 key/pair values, id and value. Here is my current code for this:
$postarray = array (
'datetime'=>'2017-02-01T14:00:00-0800',
'appointmentTypeID'=>'Appt ID',
'firstName'=>'First Name',
'lastName'=>'last Name',
'email'=>'myemail',
'phone'=>'phone #',
'fields' => array(
array('id'=>'1234', 'value'=>'Field Data')
)
);
$post = json_encode($postarray);
I have an array inside of the 'fields' array because I don't know how to add a json object with 2 values inside of an array that will then go through json_encode, as the request requires that it be converted to JSON first before being sent.
It is currently giving me this error: "{"status_code":400,"message":"The intake form field \u00221234\u0022 does not exist on this appointment." Where after "u0022" it adds on my field id. What I need is for my main array to become a JSON Object, the 'fields' to be an array, then the individual id and value pairs to be their own objects, like so (Taken Directly from Acuity Scheduling API):
{
"datetime": "2016-02-03T14:00:00-0800",
"appointmentTypeID": 1,
"firstName": "Bob",
"lastName": "McTest",
"email": "bob.mctest#example.com",
"certificate": "ABC123",
"fields": [
{"id": 1, "value": "Party time!"}
]
}
Here is Acuity Scheduling API for reference on this particular request, https://developers.acuityscheduling.com/reference#post-appointments
'fields' => array(
json_encode(array('id'=>'1234', 'value'=>'Field Data'))
)
The ID should be a number, not a string, so don't put it in quotes.
$postarray = array (
'datetime'=>'2017-02-01T14:00:00-0800',
'appointmentTypeID'=>'Appt ID',
'firstName'=>'First Name',
'lastName'=>'last Name',
'email'=>'myemail',
'phone'=>'phone #',
'fields' => array(
array('id'=> 1234, 'value'=>'Field Data')
)
);
If you're getting the ID from a script parameter, use intval() to convert it from a string to a number.
I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname#smsfree4all.com"
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);
This works fine. But what I am not sure about is how do I encode the properties in PHP with nested key value pairs shown below:
{
"username": "admin",
"password": "p4ssword",
"name": "Administrator",
"email": "admin#example.com",
"properties": {
"property": [
{
"#key": "console.rows_per_page",
"#value": "user-summary=8"
},
{
"#key": "console.order",
"#value": "session-summary=1"
}
]
}
}
What is this with # before key value?
Something like this should do it
$username="admin"; //more variables
$params=compact('username' /* more variables to be compacted here*/);
$params["properties"] = [
"property" => [
[
"#key" => "console.rows_per_page",
"#value"=> "user-summary=8"
],
[
"#key"=> "console.order",
"#value"=> "session-summary=1"
]
]
];
echo json_encode($params);
The manual has more examples you can use
Notice that:
A key~value array is encoded into an object
A regular array (array of arrays here) is encoded into an array
Those are all the rules you need to consider to encode any arbitrary object
Something like this perhaps?
$properties = [
'property' => [
['#key' => 'console.rows_per_page', '#value' => 'user-summary=8'],
['#key' => 'console.order', '#value' => 'session-summary=1']
]
];
It's difficult to tell what you're asking.
You can nest in PHP using simple arrays, very similar to JavaScript objects:
$grandparent = array(
"person1" => array(
"name" => "Jeff",
"children" => array(
array("name" => "Matt"),
array("name" => "Bob")
)
),
"person2" => array(
"name" => "Dillan",
"children" => array()
)
);
I'm trying to generate a JSON object using PHP to be passed to the client using data that is already stored in MySQL database.
The database contains a list of multipolygon coordinates like below in a single text field:
[
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
When I try to generate a JSON object using json_encode I get the following:
{
"coordinates": "[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]"
}
And because of the quotes around the coordinates themselves, they are not recognised as JSON object by JavaScript.
I've tried to explode the coordinate string and then put it back together manually but it still needs a lot of hacks to get it working.
Any help in getting this to output as a an actual JSON object in PHP would be much appreciated.
I'm trying to get to this:
{
"coordinates": [
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
}
It's pretty jerry-rigged, but you could do this:
$string = json_encode( $database_value ); // same as you're using now
$string = str_replace( '"', '', $string ); // get rid of the quotes
// wrap them back around 'coordinates'
$string = str_replace( 'coordinates', '"coordinates"', $string );
Simply use json_decode before json_encode, like this:
// This comes from the database, of course
$coords = '[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]';
echo json_encode(array(
'coordinates' => json_decode($coords)
));
This will output nested arrays exactly as you desire:
{"coordinates":[[[[104.39209,-4.850154],[108.171386875,-3.7217451958279],[112.126465,-1.274309],[103.029785,-3.579213]]]]}