Получить первый массив из нескольких конечных точек асинхронного запроса

#php #arrays #asynchronous #promise #guzzle

Вопрос:

У меня настроена программа guzzle, которая в настоящее время использует GetAsync с обещанием 4 URL. Возврат этих данных поставляется с 2 массивами, приведенными ниже в этом формате.

Мой вопрос: как я могу разделить две переменные, первая из которых является просто первым массивом? В этом примере это будет весь массив размеров 3154, а в другой переменной-весь массив размеров 10297

Жрать

 $requests = [
            getenv('apiSavingNew'), 
            getenv('apiSavingOld'),
        ];

        $promises = (function () use ($requests) {
        $client = new Client([
            'verify' => false
        ]);

        foreach ($requests as $request) {
            yield $client->getAsync($request);      
        }
        })();

        $eachPromise = new EachPromise($promises, [
            'concurrency' => 2,
            'fulfilled' => function (Response $response) {
            if ($response->getStatusCode() == 200) {
                $request = json_decode($response->getBody());
                    $firstRequest = // first array here
                    $secondRequest = // second array here
                }
            },
            'rejected' => function (RequestException $e) {
                echo $e->getMessage();
            }
        ]);

        $eachPromise->promise()->wait();
 

Вернуть обещание жрать

 array (size=3154)
  0 => 
    object(stdClass)[11532]
      public 'id' => string '57a64bb0-1c6a-11ec-bfd3-173b9227de8c' (length=36)
      public 'createdAt' => string '2021-09-23T12:32:40.427Z' (length=24)
      public 'data' => string '2021-09-22T00:00:00.000Z' (length=24)
      public 'dataFim' => string '2021-10-22T00:00:00.000Z' (length=24)
      public 'valor' => string '0.30120' (length=7)
      public 'serieTemporalId' => string 'a43978f1-7fd4-4550-9907-106474e64ee4' (length=36)
      public 'acumuladoAno' => null
      public 'acumulado12Meses' => null
  1 => 
    object(stdClass)[11539]
      public 'id' => string '57a49e00-1c6a-11ec-bfd3-173b9227de8c' (length=36)
      public 'createdAt' => string '2021-09-23T12:32:40.416Z' (length=24)
      public 'data' => string '2021-09-21T00:00:00.000Z' (length=24)
      public 'dataFim' => string '2021-10-21T00:00:00.000Z' (length=24)
      public 'valor' => string '0.30120' (length=7)
      public 'serieTemporalId' => string 'a43978f1-7fd4-4550-9907-106474e64ee4' (length=36)
      public 'acumuladoAno' => null
      public 'acumulado12Meses' => null
   more elements...

array (size=10297)
  0 => 
    object(stdClass)[11545]
      public 'id' => string '54f70a30-1c6a-11ec-bfd3-173b9227de8c' (length=36)
      public 'createdAt' => string '2021-09-23T12:32:35.923Z' (length=24)
      public 'data' => string '2021-09-22T00:00:00.000Z' (length=24)
      public 'dataFim' => string '2021-10-22T00:00:00.000Z' (length=24)
      public 'valor' => string '0.50000' (length=7)
      public 'serieTemporalId' => string 'ec940ca2-7da8-4a75-ae7b-d90244797b65' (length=36)
      public 'acumuladoAno' => null
      public 'acumulado12Meses' => null
  1 => 
    object(stdClass)[11557]
      public 'id' => string '54f3fcf0-1c6a-11ec-bfd3-173b9227de8c' (length=36)
      public 'createdAt' => string '2021-09-23T12:32:35.903Z' (length=24)
      public 'data' => string '2021-09-21T00:00:00.000Z' (length=24)
      public 'dataFim' => string '2021-10-21T00:00:00.000Z' (length=24)
      public 'valor' => string '0.50000' (length=7)
      public 'serieTemporalId' => string 'ec940ca2-7da8-4a75-ae7b-d90244797b65' (length=36)
      public 'acumuladoAno' => null
      public 'acumulado12Meses' => null
   more elements...
 

Комментарии:

1. итак, вам нужен массив для каждого запроса?

2. Вы можете передать вторую переменную $index в fulful и передать ее в качестве имени ключа для переменной, объявленной отдельно

Ответ №1:

Я не совсем понял, в чем заключается ваше требование? но все же я надеюсь, что это может помочь. Вы можете добавить второй аргумент для функции в function как $index и добавить его в отдельную переменную для пустого массива $results.

 $results = [];
$requests = [
    getenv('apiSavingNew'), 
    getenv('apiSavingOld'),
];

$promises = (function () use ($requests) {
$client = new Client([
    'verify' => false
]);

foreach ($requests as $request) {
    yield $client->getAsync($request);      
}
})();

$eachPromise = new EachPromise($promises, [
    'concurrency' => 2,
    'fulfilled' => function (Response $response, $index) {
    if ($response->getStatusCode() == 200) {
        //$request = json_decode($response->getBody());
        $results[$index] = json_decode($response->getBody(), true);
        }
    },
    'rejected' => function (RequestException $e, $index) {
        echo $e->getMessage();
    }
]);

$eachPromise->promise()->wait();