【问题标题】:php | dynamic api callphp |动态api调用
【发布时间】:2018-03-02 21:44:24
【问题描述】:

我正在尝试为我正在创建的 API 创建一个动态端点,以便包含一些数据,但前提是它是必需的,以便我可以在多个地方使用它。

这个想法是让api.domain.com/vehicle 带回基本的车辆信息,但如果我做了api.domain.com/vehicle?with=owners,history,那么想法是有一个函数将ownershistory 映射到一个将返回数据但仅在需要时。

这是我目前拥有的。

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);

标签: php api endpoint


【解决方案1】:

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) ;
}

【讨论】:

  • @IncredibleHat return $propertyMap[$property];getPropertyResponse() 中,而不是在Vehicle::history($id) 中。
  • @IncredibleHat :) 感谢您的评论,这很有趣。我正在寻找。
  • @IncredibleHat static::getPropertyResponse($property) 返回"owners": {"name": "owner name"}。同意?所以在 foreach 中,$result[$property] = static::getPropertyResponse($property)[$property]。没有?
  • 喜欢...我不确定他从getPropertyResponse 的方法中从哪里得到$id。它没有传入,也不是类引用。同样正如您所提到的,Vehicle::history() 的实际回报是多少?我迷路了。
  • 我敢打赌,你一定成功了。你的回答绝对应该是他的问题的解决方案。
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 2012-07-17
  • 2014-07-30
  • 2019-11-09
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 2019-04-25
相关资源
最近更新 更多