繁体   English   中英

在GET中使用array_filter

[英]Use array_filter in GET

我对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$dato->weight == $weight得到正确的结果。 问题是在变量$weight ,因为这$weight我得到错误: Undefined variable: weight 变量$weight在array_filter之外定义。 但是,如果我在数组内定义$weight ,则由于以下错误而无法获得权重: Undefined variable: args

任何想法?

要在闭包/匿名函数中使用变量,您需要像use($weight)一样传递它们

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM