有没有一种比较两个数组的快速方法,其中第二个数组包含第一个数组中的所有键,但还有其他键?
例如,给定下面的两个数组,我希望第一个数组中的最后两个元素在第二个数组中不存在:
$input = [
[
'firstName' => 'Paula',
'lastName' => 'Fisher',
'companyName' => 'Ankunding-Braun'
],
[
'firstName' => 'Elliot',
'lastName' => 'Roob',
'companyName' => 'Feeney PLC'
],
[
'firstName' => 'Jammie',
'lastName' => 'Morar',
'companyName' => 'Pollich PLC'
],
[
'firstName' => 'Tyrell',
'lastName' => 'Mills',
'companyName' => 'Oberbrunner, Kulas and Rice'
],
[
'firstName' => 'Fred',
'lastName' => 'Johnson',
'companyName' => 'Pollich PLC'
],
[
'firstName' => 'Tyrell',
'lastName' => 'Bloggs',
'companyName' => 'BBC East'
],
];
$output = [
[
"id" => 1,
"firstName" => "Paula",
"lastName" => "Fisher",
"salutation" => "Prof.",
"email" => "jane.fritsch@gutmann.com",
"phone" => "1-887-271-5742 x394",
"mobileNumber" => "1-558-612-4089 x45355"
],
[
"id" => 2,
"firstName" => "Elliot",
"lastName" => "Roob",
"salutation" => "Prof.",
"email" => "reinger.keenan@hyatt.com",
"phone" => "+1-378-385-3633",
"mobileNumber" => "1-815-769-2297",
],
[
"id" => 3,
"firstName" => "Jammie",
"lastName" => "Morar",
"salutation" => "Mr.",
"email"=> "amir95@becker.com",
"phone" => "(694) 767-1593 x5966",
"mobileNumber" => "204-991-3292",
],
[
"id" => 4,
"firstName" => "Tyrell",
"lastName" => "Mills",
"salutation"=> "Mrs.",
"email" => "crist.rick@cronin.biz",
"phone" => "462-385-0569 x22876",
"mobileNumber" => "532-369-9039"
]
];
作为一点上下文,我试图返回数据库中不存在的所有记录(检查名字,姓氏和公司名称)。如果有一个更好的方法使用数据库这样做很棒,但我自己也想不到任何东西,所以我已经返回了找到的记录,现在想要从搜索到的数组中删除找到的记录 - 因此留给我不存在的记录。
答案 0 :(得分:1)
要查找结果中未找到的搜索,您可以:
// I can't "query", this is for demonstration based on the question data.
// The assumption here is that this is a hydrated to array resultset from a
// Doctrine ORM query, but it should work for any array comparison of this
// sort.
$filtered = array_filter($output, function($row) use($input) {
return array_reduce($input, function($carry, $compare) use($row) {
return $carry || (
$compare['firstName'] == $row['firstName']
&& $compare['lastName'] == $row['lastName']
// Uncomment this if you want, and have, companyName to compare.
// && $compare['companyName'] == $row['companyName']
);
});
});
$notfound = array_filter($input, function($search) use($filtered) {
// Note the negation here, this uses array_reduce() to tell us when
// there's a "hit", we're looking for $search rows with no "hit".
return !array_reduce($filtered, function($carry, $row) use($search) {
return $carry || (
$search['firstName'] == $row['firstName']
&& $search['lastName'] == $row['lastName']
// Uncomment this if you want, and have, companyName to compare.
// Note that the hydrated resultset needs to account for this.
// && $compare['companyName'] == $row['companyName']
);
});
});