【发布时间】:2018-03-02 21:44:24
【问题描述】:
我正在尝试为我正在创建的 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"
}
}
}
我将如何做到这一点,使其不与索引一起返回?
【问题讨论】:
-
代替array_push,试试array_merge。
-
不要使用数组推送。您希望将每个数组条目键入属性。使用类似的东西:
$result[$property] = static::getPropertyResponse($property);