i query the address column from the database and i pass that multiple address to the Google Geocoder API and i store that latitude and longitude result in the $coordinate variable. When i var_export($coordinate); i get the output in the below format:
'[19.0759837,72.8776559]''[47.6062095,-122.3320708]''[12.9715987,77.5945627]'
but in when use print_r(array($variablename)); i get the output in this format:
Array
(
[0] => [19.0759837,72.8776559]
)
Array
(
[0] => [47.6062095,-122.3320708]
)
Array
(
[0] => [12.9715987,77.5945627]
)
But i want the output to be in single array something like this.
Array
(
[0] => [19.0759837,72.8776559],
[1] => [47.6062095,-122.3320708],
[2] => [12.9715987,77.5945627]
)
This is php code:
<?php
// database connection code and query to fetch address column the database and pass address to geocode()
header("content-type: application/json");
header('Access-Control-Allow-Origin: *');
$config = parse_ini_file('./config.ini');
$connect = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$ordertracker = mysqli_query($connect, "select address from ordertracker");
if (!$ordertracker)
{
echo "Error fetching results: " . mysqli_error();
}
$address=array();
while($row = mysqli_fetch_assoc($ordertracker)) {
$address= $row['address'];
geocode($address);
}
function geocode($address)
{
$address = urlencode($address);
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";
$geocode=file_get_contents($url);
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
$coordinate = "[" . $lat . "," . $long . "]";
var_export($coordinate);
}
?>
If you want an array, then you should not use string literals and concatenation to build it, as that will result in a string.
Instead let your function result an array with two values (latitude and longitude) and append those pairs to your main array in your main loop:
$address = [];
while($row = mysqli_fetch_assoc($ordertracker)) {
$address[] = geocode($row['address']);
}
print_r($address);
function geocode($address) {
$address = urlencode($address);
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";
$geocode = file_get_contents($url);
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
$coordinate = [$lat, $long];
return $coordinate;
}