0

I use DomCrawler to grab some data, and I would like to know if I can get an array from a closure, here is my code :

    $promises = $products
        ->each(function(Crawler $node) use ($client, $cookieJar) {
            $href = $node->filter('a')->last()->attr('href');

            return [
                $href => $client->getAsync($this->config['url'] . $href, [
                    'cookies' => $cookieJar,
                ])
            ];
        });

It will return me like :

$promises = [
   ['href_value' => Guzzle\Promise],
   ....
 ];

But I would like to have :

$promises = [
   'href_value' => Guzzle\Promise,
   ....
 ];

How can I tranform the return statetement to have this result, something like this in my mind :

return ($href) => $client->getAsync($this->config['url'] . $href, [
        'cookies' => $cookieJar,
    ]);
Pupil
  • 23,834
  • 6
  • 44
  • 66
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
  • 1
    there's a reason why it's nested, coz it might return more than one, obviously keys must be unique. just reassign it with `reset` or point to index zero – Kevin Feb 10 '21 at 09:55

1 Answers1

0

Transform your $promises to have flat array:

$flatPromises = [];

foreach ($promises as $promise) {
    foreach ($promise as $key => $value) {
         $flatPromises[$key] = $value;
    }
}

Justinas
  • 41,402
  • 5
  • 66
  • 96