I have a case where I may recive one of two json objects, in this case from either the google geocode api, or the places api.
Acccessing values from the geocoding api it will look like this:
$coordinates = $data->results[0]->geometry->location;
$cache_value['lat'] = (string) $coordinates->lat;
$cache_value['lng'] = (string) $coordinates->lng;
and an almost identical structure for places.
$coordinates = $data->result->geometry->location;
$cache_value['lat'] = (string) $coordinates->lat;
$cache_value['lng'] = (string) $coordinates->lng;
In my code I've two functions to handle each case, but they are almost idential with the exception of the result vs results[0] and I'd like to combine them. I've tried to passing a varriable but it throws errors:
$result = ($place) ? 'result' : 'results[0]';
$coordinates = $data->$result->geometry->location;
Gives the following:
Notice: Undefined property: stdClass::$result[0]
I'd like to know the correct syntax to achive what im after, and any pointers on nominclature, as Im afraid this question title is a bit inpercise.
Just do:
$result = $place ? $data->result : $data->results[0];
$coordinates = $result->geometry->location;
What your code is doing, is this: It tries to resolve a property of $data object with a name of results[0], and there is none; Once again - it does not resolve 0 index of the results property, but it tries to find a property with a literal name results[0]; It would work if your object looked like this:
$obj = (object)array( 'results[0]' => 'hey there' );
If for any reason you would like to play with that, you could create a silly property like this: $data->{'results[0]'} = 5; - but it's stupid, don't do that :)
i believe php is looking for a key named results[0], its not smart enough to know that the properties name is results and you want the first member of the collection [0]
The issue is the reference of the variable name, rather than its value.
$result = ($place) ? 'result' : 'results[0]';
$coordinates = $data->$result->geometry->location;
$result is just a string and should be the actual value of either $data->result or $data->result[0].
To correct it, simply use $result to hold the value of result.
$result = ($place) ? $data->result : $data->results[0];
$coordinates = $result->geometry->location;
Related
I need to merge a php array INTO a php object.
I need my php object to look like this :
{"info1":"value","concurrents":[{"concurrent1":"value"},{"concurent2":"value"}],"info3":"value"};
, I'm actually getting my initial object like this :
$initial = pg_fetch_object($result);
After that, I'm getting the array with this command :
$concurrents = pg_fetch_all($result);
So please, how could i merge $concurrents INSIDE my $initial object, for executing this finally for destination to the front end:
print_r(json_encode($initial));
I've tried a foreach, but it doesn't work.
Have you tried the following?
$initial->concurrents = $concurrents;
Or even:
$initial->concurrents = pg_fetch_all($result);
Don't get your initial result as an object, get it as an array:
$initial = pg_fetch_assoc($result);
Then 'merging' is fairly easy (push the initial on to the beginning of your concurrents array):
$concurrents = pg_fetch_all($result);
array_unshift($concurrents, $initial);
Now you can print them:
print_r(json_encode($concurrents));
I am following this documentation
to implement export to Excel in my laravel 4 project.
So am trying to generate excel file from array like this:
//$results is taken with db query
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
But this raises exception:
Object of class stdClass could not be converted to string
What am I doing wrong ?
UPDATE:
Tried this:
$data = get_object_vars($data);
which results in:
get_object_vars() expects parameter 1 to be object, array given
This:
$data = (array)$data;
Results in the initial error.
Try this simple in one line of code:-
$data= json_decode( json_encode($data), true);
Hope it helps :)
$data is indeed an array, but it's made up of objects.
Convert its content to array before creating it:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Excel::create(....
You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.
You can either use
get_object_vars()
Or if its a simple object, you can just typecast it.
$arr = (array) $Object;
If you have a Collection of stdClass objects, you could try with this:
$data = $data->map(function ($item){
return get_object_vars($item);
});
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
This is easy all you need to do is something like this Grab your contents like this
$result->get(filed1) = 'some modification';
$result->get(filed2) = 'some modification2';
I'm trying to build URL query from an Array that looks like that:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
I would like to get query like that:
localhost/get?serial=3804689&serial=3801239&serial=3555689
(you get the idea)
I'm trying to use http_build_query($serials, 'serial', '&'); but it adds the numeric index to the prefix 'serial'.
Any idea how to remove that numeric index?
Well you can't really have the same GET parameter in the string, After all if you try to access that variable server side, what would you use?
$_GET['serial'] - But which serial would it get?
If you really want to get a list of serials, Simply turn the array into a string, save it as an array and there you go. for example :
$serials = "string of serials, delimited by &";
Then you can use the http build query.
Maybe use a foreach:
$get = "localhost/get?serial=" . $serials[0];
unset( $serials[0] );
foreach( $serials AS serial ){
$get .= "&serial=$serial;
}
Just as an FYI, PHP doesn't handle multiple GET variables with the same name natively. You will have to implement something fairly custom. If you are wanting to create a query string with multiple serial numbers, use a delimiter like _ or -.
Ex: soemthing.com/serials.php?serials=09830-20990-91234-12342
To do something like this from an array would be simple
$get_uri = "?serial=" . implode("-", $serials);
You would be able to get the array back from a the string using an explode to
$serials = explode("-", $_GET['serials']);
Yes its quite possible to have such format, you have to build it query string by indices. Like this:
No need to build the query string by hand, use http_build_query() in this case:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$temp = $serials;
unset($serials);
$serials['serial'] = $temp;
$query_string = http_build_query($serials);
echo urldecode($query_string);
// serial[0]=3804689&serial[1]=3801239&serial[2]=3555689&serial[3]=3804687&serial[4]=1404689&serial[5]=6804689&serial[6]=8844689&serial[7]=4104689&serial[8]=2704689&serial[9]=4604689
And then finally, if you need to process it somewhere, just access it thru $_GET['serial'];
$serials = $_GET['serial']; // this will now hold an array of serials
You can also try this
$get = "localhost/get?serial=";
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$list = implode("&serial=",$serials);
echo $get.$list;
Having the same GET parameter will not work this way. You will need to use an array in the get parameter:
localhost/get?serial[]=3804689&serial[]=3801239&serial[]=3555689
IF you just print $_GET through this URL, you will receive
Array ( [serial] => Array ( [0] => 380468 [1] => 3801239 [2]=> 3555689) )
Then you can do this to build your query string
$query_str = 'serial[]='.implode('&serials[]=',$serials);
You can try this version.
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$get = implode('&serials[]=',$serials);
echo 'test';
var_dump($_GET['serials']);
Result
I want to get polygon coordinates from below String.
{"polygon":{"type":"Feature","properties":[],"geometry":{"type":"Polygon","coordinates":[[[-7302732.4720101,6527844.6333235],[-3193477.8319711,6606116.1502766],[-5111129.9973226,5001550.0527375],[-6637424.5779086,4884142.7773079],[-7772361.5737289,5158093.0866438],[-7302732.4720101,6527844.6333235]]]},"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}}
This is GeoJson string that i decode to array with below code:
$polygon = CJSON::decode($str);
when i want to get polygon i get error!
$var= $polygon->polygon;
or with below code:
$polygon = CJSON::decode($str,true);
$var = $polygon['polygon'];
although for getting coordinates:
foreach($polygon as $key=>$value)
$coordinates = $value['coordinates'];
or
$coordinates = $value[coordinates];
how can i get coordinates from geojson that i send from javascript to php for saving on postgresql with postgis?
$polygon->polygon->geometry->coordinates[0]
or
$polygon['polygon']['geometry']['coordinates'][0]
what you have is a multidimensional array/object not sure which its being output to when decoded in your case as it appears you have a class doing it I would have just used json_decode, but anyway. Yea from the looks of it, polygon is the main object, then in it is geometry which is an object that has type and coordinates, and then coordinates has multiple objects/arrays in it.
the above samples if I typed them right will show the first set of coordinates in that object. Of course you could run it through a loop ie:
In the case that it is an object assuming your Class decodes as an object and not an array. Not exactly sure what $polygon = CJSON::decode($str,true); does. But if its anything like json_decode() then you should be all set.
This is my method of breaking down the object as you present here, its worth noting you may want to check counts, and see if the object is set first, or if the property exists in the object to prevent other means of the code breaking down the road. But what I have here is just pure example at its core, it will server its purpose though. But will not error handle which is why I say you may want to elaborate further on it doing those checks.
Anyway heres my code:
<?php
$str = '{"polygon":{"type":"Feature","properties":[],"geometry":{"type":"Polygon","coordinates":[[[-7302732.4720101,6527844.6333235],[-3193477.8319711,6606116.1502766],[-5111129.9973226,5001550.0527375],[-6637424.5779086,4884142.7773079],[-7772361.5737289,5158093.0866438],[-7302732.4720101,6527844.6333235]]]},"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}}';
$polygon = json_decode($str);
echo'<pre>';print_r($polygon);echo'</pre>';
$set = 1;
foreach($polygon->polygon->geometry->coordinates[0] as $coordinates)
{
echo 'Set '.$set.': ';$set++;
echo $coordinates[0].','.$coordinates[1].'<br>';
}
?>
see it in action http://7pz.net/geojson-parse.php (scroll to the bottom)
This should give you an array of all the coordinates and print them out line by line:
$string = '{"polygon":{"type":"Feature","properties":[],"geometry":{"type":"Polygon","coordinates":[[[-7302732.4720101,6527844.6333235],[-3193477.8319711,6606116.1502766],[-5111129.9973226,5001550.0527375],[-6637424.5779086,4884142.7773079],[-7772361.5737289,5158093.0866438],[-7302732.4720101,6527844.6333235]]]},"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}}';
$json = json_decode($string);
$coords_array = $json->polygon->geometry->coordinates[0];
foreach($coords_array as $c_a) {
echo $c_a[0] . "," .$c_a[1] . "<br>";
}
Access with:
$coords_array[0];
$coords_array[1];
$coords_array[2];
etc.
Basically you can turn the JSON string into an object and access each element with the -> notation.
I usally use a site called http://jsonviewer.stack.hu/ to decode JSON and find the path I need, then simply write them out as they appear, as in as in the above - $json->polygon->geometry->coordinates;.
Try it out yourself on the site.
I'm not a PHP developer so I may be doing something wrong. I'm trying to decode JSON string and insert some values to mysql database. I'm getting a valid array of json objects (tested with jsonlint), so I'm adding them one by one to database. But php throws :
<b>Fatal error</b>: Cannot use object of type stdClass as array error.
This is the code :
$array = json_decode(stripslashes($_POST['data']));
for($i = 0, $l = sizeof($array); $i < $l; $i++){
$obj = $array[$i];
echo "ARRAY1: ".$array;
echo "L: ".$l;
echo "ARRAY2: ".gettype($array);
$q = 'INSERT INTO dependencies SET projectID = "1", `from` = "'.$obj->{'From'}.'", to = "'.$obj->{'To'}.'", type = "'.$obj->{'Type'}.'", cls = "'.$obj->{'Cls'}.'", lag = "'.$obj{'Lag'}.'"';
Error is thrown from line $q = 'INSERT INTO... and the printed variables show that indeed my $array is an Array :
ARRAY1: ArrayL: 2ARRAY2: array . What am I doing wrong here ?
json_decode returns an object, unless you specify you want an array with the second optional argument:
json_decode(stripslashes($_POST['data']), true);
Some other useful advice:
Use var_dump for debugging purposes. It will help you understand the structure of any objects/arrays in your code.
You should not be accepting data through post and the using it in an SQL query without any sanitation, anyways. I highly recommend you fix that asap.
You're missing a -> in the last assignment:
$obj{'Lag'}
The simplest way is as Paul pointed out and I'd advise this one. But if you ever need to cast an array as an object use:
$newObject = (object) $oldArray;