如何将PHP中的值从函数传递到数组

时间:2016-11-24 21:18:21

标签: php arrays foreach

我已经阅读了有关此主题的问答,但遗憾的是我没有回答我的问题,因为我是PHP的初学者。

我使用函数在Google地图上显示多边形。这一切都很好。 coords存储在以下变量中:

$polygon = array(
"43.231297 -79.813721",
"43.238438 -79.810768",
"43.230335 -79.809395",
"43.230312 -79.809296",
"43.240208 -79.808983",
"43.230225 -79.808884",
"43.240116 -79.808617",
"43.229823 -79.807388",
"43.231235 -79.802649",
"43.237137 -79.800774",
"43.231297 -79.813721"
);

我现在想要从MySQL数据库中动态获取纬度和经度。我的代码运行良好并返回所需的坐标:

            <?
                foreach ($BusinessAreaMunich as $item) {
                echo "new google.maps.LatLng(" .$item['AreaCoordLatitude'] . "," .$item['AreaCoordLongitude'] . "), \n";
            }
            ?>

但是,我已尝试执行以下操作:

$polygon = array(
    foreach ($BusinessAreaMunich as $item) {
    echo $item['AreaCoordLatitude'], $item['AreaCoordLongitude'];
}
);

现在我知道这不起作用,但我不知道如何解决我的问题。你能告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:-1)

正确的代码是:

$polygon = array();  // define `$polygon` as array
foreach ($BusinessAreaMunich as $item) {
    // create `string` value as a result of concatenating coords and a space
    $coords = $item['AreaCoordLatitude'] . ' ' . $item['AreaCoordLongitude'];

    // append a `string` to `$polygon`
    $polygon[] = $coords;

    // or simply:
    // $polygon[] = $item['AreaCoordLatitude'] . ' ' . $item['AreaCoordLongitude'];
}

// output to see what you have
print_r($polygon);