我在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
,我无法获得权重。
有什么想法吗?
答案 0 :(得分:2)
要在closure/anonymous functions中使用变量,您需要将其作为use($weight)
传递给
$provider_filter = array_filter($destination, function ($data) use($weight) {
return $data->weight == $weight;
});