return 包含某些项目的数组,前提是它们存在于另一个数组中

return array with some items only if they exist in another array

我想要一个函数,它有一个包含一些顶级产品的初始数组,并且应该 return 一个包含 $topProds 数组中存在的项目的数组。

$topProds = ['laptop', 'printer', 'keyboard', 'monitor', 'usb adaptor'];

该函数接收来自 API (array $prod) 的一些信息,并且应该 return 具有以下格式的数组:

prods: [
    
    {
        label: 'Laptop',
    },
    {
        label: 'Printer',
    },
    {
        label: 'Usb Adaptor',
    }
],

只有存在于 topProds 数组中的产品才应该被 returned。例如,在某些情况下,可能存在 'paper' 产品,但由于它不在 $topProds 数组中,因此不应在函数上 returned。

我正在尝试使用下面的函数来实现它,但是像这样它不起作用。我不明白除了地图,如何 return 仅存在于 $topProds 数组中的项目。

public function getTopProducts(array $prod): array
    {
        $topProds = ['laptop', 'printer', 'keyboard', 'monitor', 'usb adaptor'];
    
        collect($prod['content']['data'])->map(function ($prod) {
            return [
                'label' => $prod['title'],
            ];
        });
    }

带有过滤器的示例:

$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