我有以下数组名为investmentprogramcriteria和companyinvestmentprofile:
Array
(
[0] => Array
(
[investmentprogramcriteriaID] => 20
[investmentprogramID] => 21
[criteriaID] => 59
[criteriaIsMatchedIf] => 1
)
[1] => Array
(
[investmentprogramcriteriaID] => 21
[investmentprogramID] => 21
[criteriaID] => 57
[criteriaIsMatchedIf] => 1
)
)
Array
(
[0] => Array
(
[investmentprofileID] => 1
[companyID] => 27
[criteriaID] => 54
[investmentprofileCriteriaAnswer] => 1
)
[1] => Array
(
[investmentprofileID] => 2
[companyID] => 27
[criteriaID] => 57
[investmentprofileCriteriaAnswer] => 0
)
[2] => Array
(
[investmentprofileID] => 3
[companyID] => 27
[criteriaID] => 58
[investmentprofileCriteriaAnswer] => 0
)
[3] => Array
(
[investmentprofileID] => 4
[companyID] => 27
[criteriaID] => 59
[investmentprofileCriteriaAnswer] => 1
)
)
如果第一个数组中的最后两个key AND THEIR VALUES在第二个数组中找到,代码应该返回match,
返回not match。我尝试用数组函数来解决这个问题,但没有任何工作,现在我试图用php来解决它,但到目前为止还没有运气。
我正在尝试:
foreach ($investmentprogramscriteria as $programcriteria) {
//foreach($companyInvestmentProfil as $profile) {
if (($programcriteria['criteriaID'] == $companyInvestmentProfil[$i]['criteriaID']) && ($programcriteria['criteriaIsMatchedIf'] == $companyInvestmentProfil[$i]['investmentprofileCriteriaAnswer'])) {
$match = "Match";
} else {
$match = "Not Match";
continue;
// }
}
}
最好的方法是使用foreach两次!!
foreach ($investmentprogramscriteria as $value) {
foreach ($companyInvestmentProfil as $v) {
if($v["criteriaID"] == $value["criteriaID"]) echo "match<br>";
else echo "not Match<br>";
}
}
更新
你的代码包含一个bug:
$programcriteria['criteriaID'] == $companyInvestmentProfil[$i]['criteriaID']
变量$i
从未定义。你可能想写这样的东西:
// assign keys to $i
foreach ($investmentprogramscriteria as $i => $programcriteria) {
}
在这种情况下,使用下面的array_slice
+ array_keys
方法,带或不带array_intersect_assoc
方法应该工作,如果您分别在$programcriteria
和$companyInvestmentProfil[$k]
数组上使用它们。
你基本上要找的是array_intersect_assoc
函数。该函数返回一个数组,其中包含两个数组中存在的所有键值对:
$intersect = array_intersect_assoc($array1, $array2);
查看有多少键值对匹配,只需count($intersect);
查看第一个数组的最后两个键是否匹配,只需这样写:
$lastKeys = array_slice(array_keys($array1), -2);
if (isset($intersect[$lastKeys[0]]) && isset($intersect[$lastKeys[1])) {
return 'match';
}
return 'no match';
查看array_slice
的详细信息。
$array1 = array("a" => "greens", "reds", "blues", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
if(is_array($result)){
echo 'match';
}else{
echo 'not match';
}