在GET

时间:2018-05-16 10:34:35

标签: php get doctrine

我在GET请求时遇到了一些问题。此请求有两个要过滤的参数:

$app->get('/api/v1/provider/{destination}/{weight}', function ($request, $response, $args) {

   $em = getEntityManager();
   $destination = $em->getRepository(Transport::class)->findByDestination($args['destination']);
   $weight = $em->getRepository(Transport::class)->findByWeight($args['weight']);

     $provider_filter = array_filter($destination, function ($data) {
        return $data->weight == $weight;    
    });

    return $response->withJson($provider_filter);
});

例如,如果我写$dato->weight == 3而不是$dato->weight == $weight,我会得到正确的结果。问题出现在变量$weight中,由于$weight我收到错误:Undefined variable: weight。变量$weight在array_filter之外定义。然而,如果我在数组中定义$weight,由于错误:Undefined variable: args,我无法获得权重。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

要在closure/anonymous functions中使用变量,您需要将其作为use($weight)传递给

$provider_filter = array_filter($destination, function ($data) use($weight) {
    return $data->weight == $weight;    
});