PHP Closure - Return an array with key / value
Get the solution ↓↓↓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,
]);
Answer
Solution:
Transform your$promises
to have flat array:
$flatPromises = [];
foreach ($promises as $promise) {
foreach ($promise as $key => $value) {
$flatPromises[$key] = $value;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: attempt to read property "id" on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.