Использовать array_filter в GET - PullRequest
0 голосов
/ 16 мая 2018

У меня проблемы с запросом 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 голосов
/ 16 мая 2018

Чтобы использовать ваши переменные внутри замыкания / анонимных функций , вам нужно передать их как use($weight) как

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