簡體   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