我从数据库中查询地址列,然后将该多个地址传递给Google Geocoder API,并将该纬度和经度结果存储在$coordinate
变量中。当我var_export($coordinate);
我得到以下格式的输出:
'[19.0759837,72.8776559]''[47.6062095,-122.3320708]''[12.9715987,77.5945627]'
但在使用print_r(array($variablename));
时,我得到这种格式的输出:
Array
(
[0] => [19.0759837,72.8776559]
)
Array
(
[0] => [47.6062095,-122.3320708]
)
Array
(
[0] => [12.9715987,77.5945627]
)
但我希望输出在单个数组中,就像这样。
Array
(
[0] => [19.0759837,72.8776559],
[1] => [47.6062095,-122.3320708],
[2] => [12.9715987,77.5945627]
)
这是php代码:
<?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);
}
?>
答案 0 :(得分:0)
如果你想要一个数组,那么就不应该使用字符串文字和连接来构建它,因为这会产生一个字符串。
而是让你的函数产生一个带有两个值(纬度和经度)的数组,并将这些对附加到主循环中的主数组中:
$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;
}