我正在尝试为我创建的API创建一个动态端点,以便包含一些数据,但只有在需要时才能在多个地方使用它。
想法是让api.domain.com/vehicle
带回基本的车辆信息但是如果我做了api.domain.com/vehicle?with=owners,history
那么想法是有一个函数将owners
和history
映射到一个类,它将返回数据,但仅在需要时。
这就是我现在拥有的。
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
然后将调用此函数。
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
但是,我得到的响应是嵌套在索引中,我不希望它。我想要的格式是......
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
但我得到的格式是......
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
我怎么做这个,所以它不返回索引?
Vehicle::history($id)
似乎返回['history'=>['year' => '26/01/2018']]
,...等。
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
或者你的方法应该返回类似['year' => '26/01/2018']
的东西并使用:
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}