PHP 和 JSON:返回合适的格式


PHP and JSON: Returning a suitable format

我正在尝试使用谷歌地图方向API从数据库中绘制连接城市的路线。我的问题是我被困在应该通过 json 从 php 脚本返回值的点上。我要映射的数据通知一个数组:

$data=array('chicago','new york','lebanon','maysvile','greenfield');

我的目的是从我的数据数组中返回以下格式。

var request = {
   origin:start, 
   destination:end,
   waypoints:[{
         location:"",
         stopover:true
   }],
   travelMode: google.maps.DirectionsTravelMode.DRIVING
}

这就是我获得起点和目的地的方式:数组中的第一个和最后一个元素:

$start=reset($data);     
$end=end($data);

php 使用 json_encode() 返回的数据

    $response=array('origin'=>$start,'destination'=>$end,'travelMode'=>"google.maps.DirectionsTravelMode.DRIVING");
echo json_encode($response);

返回的格式不正确。我也不知道我应该如何做中点。中点是选取$start和$end后剩余的所有值。任何想法都受到高度赞赏。谢谢

$response = array(
    'origin' => array_shift($data),
    'destination' => array_pop($data),
    'waypoints' => array(),
    'travelMode' => 'DRIVING'
);
foreach($data as $wp) {
    $response['waypoints'][] = array('stopover' => true, 'location' => $wp);
}
echo json_encode($response);

请注意,array_shiftarray_pop修改$data数组!

脚本的输出为:

{
    "origin": "chicago",
    "destination": "greenfield",
    "waypoints": [
        {
            "stopover": true,
            "location": "new york"
        },
        {
            "stopover": true,
            "location": "lebanon"
        },
        {
            "stopover": true,
            "location": "maysvile"
        }
    ],
    "travelMode": "DRIVING"
}

当你从 PHP 得到响应时,它将是一个字符串,包含 JSON 格式的数据。

您将需要使用:

var myObject = JSON.parse(stringOfJson);

将其转换为 JSON 对象。

如果你想要数据的PHP表示,为什么不在PHP中创建一个对象来表示它:

class RouteInformation 
{
    public $Origin;
    public $Destination;
    public $Waypoints;
    public $TravelMode;
    public function __construct() 
    {
        $this->Waypoints = array();
    }
}

然后,您可以将此对象序列化为 JSON,它将采用所需的格式。

$response = new RouteInformation();
$response->Origin = array_shift($data);
$response->Destination = array_pop($data);
$response->TravelMode = 'DRIVING';
foreach($data as $wp) {
    $response->Waypoints[] = array('stopover' => true, 'location' => $wp);
}
echo json_encode($response);

您可以更进一步,创建一个 Waypoint 类来表示数组中的每个 Waypoint。