'return array with some items only if they exist in another array
I want to have a function that has an initial array with some top products and should return an array with the items that exist on the $topProds array.
$topProds = ['laptop', 'printer', 'keyboard', 'monitor', 'usb adaptor'];
The function receives some information that comes from an API (array $prod) and should return an array with this format:
prods: [
{
label: 'Laptop',
},
{
label: 'Printer',
},
{
label: 'Usb Adaptor',
}
],
Only the products that exist on the topProds array should be returned. For example there there might be cases where there there is a 'paper' product but since its not in the $topProds array should not be returned on the function.
I'm trying to achieve that with the function below, but like this it doesn't work. Im not understanding how to besides the map, how to return only the items that exist on the $topProds array.
public function getTopProducts(array $prod): array
{
$topProds = ['laptop', 'printer', 'keyboard', 'monitor', 'usb adaptor'];
collect($prod['content']['data'])->map(function ($prod) {
return [
'label' => $prod['title'],
];
});
}
Solution 1:[1]
Example with filter:
$topProds = collect(['laptop', 'printer', 'keyboard', 'monitor', 'usb adaptor']);
$prods = collect(['laptop', 'printer', 'monitor', 'usb']);
$res = $prods->filter(function ($value, $key) use ($topProds) {
return $topProds->contains($value); //return only if $topProds contains the current $value in the $prods collection
})->map(function($val){
return [ 'label' => ucwords($val)];
});
$res->all(); //outputs similar to your result but array of arrays. You can use json_encode([ 'label' => $val]) if you want json objects
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3532758 |
