我在Laravel中有2个Collections,我只想在$result
对象中使用通用值。我看到$collection->intersect()
仅适用于一维数组。
以下是收藏集
Collection {#1086 ▼
#items: array:5 [▼
0 => {#1115 ▼
+"name": "Light"
+"class": "ABC"
+"id": 4
}
1 => {#1113 ▼
+"name": "Milo"
+"class": "XYZ"
+"id": 10
}
2 => {#1120 ▼
+"name": "Milo Test"
+"class": "ABC"
+"id": 12
}
3 => {#1102 ▼
+"name": "KMSMiloCow"
+"class": "ABC"
+"id": 16
}
4 => {#1106 ▼
+"name": "MiloCows"
+"class": "XYZ"
+"id": 18
}
]
}
Collection {#1086 ▼
#items: array:5 [▼
0 => {#1115 ▼
+"name": "Light"
+"class_name": "ABC"
+"id": 4
}
]
}
现在,我只需要这个
Collection {#1086 ▼
#items: array:5 [▼
0 => {#1115 ▼
+"name": "Light"
+"class": "ABC"
+"id": 4
}
]
}
答案 0 :(得分:0)
我认为使用收集方法each
和contains
,可以像这样
$collection1->each(function ($value, $key) use ($collection2){
return $collection2->contains($value);
});
dd($collection1);
我在路由文件web.php中对其进行测试
use Illuminate\Support\Collection;
Route::get('test', function(){
$collection1 = new Collection([
'bear',
'whale',
'chicken',
'tardigrade'
], [[
'bear8',
'whale44',
'chicken45',
'tardigrade445'
]]);
$collection2 = new Collection([
'bear1',
'whale2',
'chicken3',
'tardigrade4'
], [[
'bear',
'whale',
'chicken',
'tardigrade'
]]);
$collection1->each(function ($value, $key) use ($collection2){
return $collection2->contains($value);
});
dd($collection1);
});
答案 1 :(得分:0)
尝试
$a1 = array(
array('name' => 'asdfjkl;', 'class' => 'foo'),
array('name' => 'qwerty', 'class' => 'bar'),
array('name' => 'uiop', 'class' => 'baz'),
);
$a2 = array(
array('name' => 'asdfjklk;', 'class' => 'foo'),
array('name' => 'qwertyxs', 'class' => 'bar'),
array('name' => 'uiop', 'class' => 'baz'),
);
$cc = array_uintersect($a1, $a2, 'cmp');
print_r($cc);
function cmp($a1, $a2){
return strcasecmp($a1['name'] , $a2['name']);
}
答案 2 :(得分:0)
我不知道这对您有没有帮助,但是这些会有用
replace(/<a href="(.*)"/g, '<a href="$1/index.html"')
答案 3 :(得分:0)
要获取包含公共元素的集合,您可以使用 filter():
<块引用>filter 方法使用给定的回调过滤集合,只保留那些通过给定真值测试的项目
$commonCollection = $collection1->filter(function ($value, $key) use ($collection2){
return $collection2->contains($value);
});