Search code examples
phpgetdoctrine

Use array_filter in GET


I have some problems with GET request. This request has two parameters to filter:

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

For example , if I write $dato->weight == 3 instead of $dato->weight == $weight, I get correct result. The problem is in the variable $weight, due to which $weight I get the error: Undefined variable: weight. The variable $weight is defined outside the array_filter. Nevertheless, if I defined $weight inside the array I can't get the weight because of the error: Undefined variable: args.

Any idea?


Solution

  • To use your variables inside closure/anonymous functions you need to pass them as use($weight) like

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