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);
Related
I have a big chunk of data in this format:
[
{"date":"2018-11-17"},{"weather":"sunny"},{"Temp":"9"},
{"date":"2014-12-19"},{"Temp":"10"},{"weather":"rainy"},
{"date":"2018-04-10"},{"weather":"cloudy"},{"Temp":"15"},
{"date":"2017-01-28"},{"weather":"sunny"},{"Temp":"12"}
]
Is there any faster and more efficient way to organize and save it the database for future reference? Like making a comparison of the temperature for different days etc. [date,weather,Temp] are supposed to be in one set.
I've tried str_replace() but I'd like to know if there's any better way.
Taking into account your comment, it seems that is an array of objects in which every three objects make a record (that is form of: date, weather & temp) so you can create this setup with the help of collections:
$string = ['your', 'json', 'string'];
$records = collect(json_decode($string))
->chunk(3) // this creates a subset of every three items
->mapSpread(function ($date, $weather, $temp) { // this will map them
return array_merge((array) $date, (array) $weather, (array) $temp);
});
This will give you this output:
dd($records);
=> Illuminate\Support\Collection {#3465
all: [
[
"date" => "2018-11-17",
"weather" => "sunny",
"Temp" => "9",
],
[
"date" => "2014-12-19",
"Temp" => "10",
"weather" => "rainy",
],
[
"date" => "2018-04-10",
"weather" => "cloudy",
"Temp" => "15",
],
[
"date" => "2017-01-28",
"weather" => "sunny",
"Temp" => "12",
],
],
}
PS: To get the array version of this collections just attach ->all() at the end.
You can check in the Collections documentation a good explanation of the chunk() and mapSpread() methods as well of the rest of the available methods.
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": ...}
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()
)
);
This question already has answers here:
create nested JSON object in php?
(7 answers)
Closed last year.
I have to comunicate with some API which expect JSON.
Until now I was fine because I needed just simple json so I just create array like this:
$data = array (
"firstName" => "TEXT1",
"lastName" => "TEXT2",
"license" => "TEXT3",
"password" => "TEXT4",
"username" => "TEXT5"
);
And after that just simple
$data_string = json_encode($data);
So final JSON looks like:
{
"firstName": "TEXT1",
"lastName": "TEXT2",
"license": "TEXT3",
"password": "TEXT4",
"username": "TEXT5"
}
However now I have to change it a bit and I am confuse, my new JSON shoud looks like:
{
"contact": {
"city": "New Yourk",
"email": "my#mail.com",
"phone": "777888999",
"postCode": "07101",
"street": "Street N. 12"
},
"enabled": true,
"firstName": "Robert",
"lastName": "Exer",
"username": "login#login.com",
"license": "text",
"password": "text"
}
As you can see it is basicly just added contact part. I was thinking how I can do this but only think I found was something like to insert array to existing $data array and then json_encode this but this will not give me a contract: at start.
Of course there is possible to do it some other way like create one json and then another and hardly connect string and so on. But i believe there have to be some better way how to do things like this.
I apprciate any advise:)
Just put an array in the value of contact:
$data = array(
'contact' => array(
'city' => 'New York',
'email' => 'my#mail.com',
//...
),
'enabled' => true,
'firstName' => 'Robert',
'lastName' => 'Exer',
//...
);
$data_string = json_encode($data);
An array can contain another array, which will be encoded as a separate object inside the previous object:
$data = array (
"contact" => array(
"city" => "New Yourk",
"email" => "my#mail.com",
"phone" => "777888999",
"postCode" => "07101",
"street" => "Street N. 12"
),
"enabled": true,
.. etc
);
I made a small library to read database-exported xml file, and output it as an structured associate array. It can also filter the output by table columns.
After I've done the code, when I play with this class I find something weird. unset is acting as if the variable was passed by reference.
I could not spot any possible bugs, so I put up my the particular method where $this->rows is being set, hoping someone could enlight me.
private function populateData($rowLimit)
{
if (!$this->getColumns()) {
throw new ReaderException(__FUNCTION__ . " # Unable to get columns name.");
}
// database->tableName->rows
$rows = $this->getSimpleXmlElement()->children()->children();
if ($this->getFilteredColumns()) {
$toRemoves = array_values(array_diff($this->getColumns(),
$this->getFilteredColumns()));
foreach ($rows as $row) {
foreach ($toRemoves as $toRemove) {
unset($row->{$toRemove});
}
}
}
$rows = $this->simpleXmlToArray($rows)['row'];
if ($rowLimit) {
$limited = [];
for ($i = 0; $i < $rowLimit; $i++) {
$limited[] = $rows[$i];
}
$this->setRows($limited);
} else {
$this->setRows($rows);
}
$structArray = [
'database' => $this->getDatabaseName(),
'table' => $this->getTableName(),
'columns' => !$this->getFilteredColumns() ? $this->getColumns()
: $this->getFilteredColumns(),
'rows' => $this->getRows()
];
$this->setStruct($structArray);
return $this;
}
$xml = new SomeXmlReader($companyTableFilePath);
$xml->get(1);
output:
[
"database" => "myDatabase",
"table" => "companies",
"columns" => [
"id",
"name",
"license_no",
"phone",
"created",
"modified",
],
"rows" => [
[
"id" => "1",
"name" => "SOME COMPANY NAME",
"license_no" => "884652",
"phone" => null,
"created" => "2015-09-25 16:01:57",
"modified" => "2015-09-25 16:01:57",
],
],
]
When I tried to filter off some columns, I do
$xml->setFilteredColumns(['id','name'])->get(1);
it returns the result as expected: the columns have been trimmed.
Output:
[
"database" => "myDatabase",
"table" => "companies",
"columns" => [
"id",
"name",
],
"rows" => [
[
"id" => "1",
"name" => "SOME COMPANY NAME",
],
],
]
However, right after this line, when I test it again with
$xml->setFilteredColumns(['id','name','phone'])->get(1);
on the next line, something went wrong. The output is:
[
"database" => "myDatabase",
"table" => "companies",
"columns" => [
"id",
"name",
"phone",
],
"rows" => [
[
"id" => "1",
"name" => "SOME COMPANY NAME",
],
],
]
After some tracing, I find that $this->getSimpleXmlElement() had been modified by unset. Within this app lifecycle, I can no longer get the complete/original value of $this->getSimpleXmlElement().
Is there a fundamental mistake I've made, or this is a PHP language behaviour?
There is rather a lot of code to follow through here - consider making a more compact example - but it sounds like your misunderstanding is fairly simple.
Objects are never copied when going from one scope to another, because a variable doesn't "contain" an object, it "points at" one (this is not quite the same as pass-by-reference, but the effect is similar in many cases).
So when you run unset($row->{$toRemove});, you are indeed editing the $row object, and by extension the whole SimpleXML document.
If you want a copy of an object to work with, you have to explicitly "clone" it, as discussed in the PHP manual.