我有两个成员数相同的数组(总是)$userInputArr=array("z","z","E","z","z","E","E","E","E","E");
和$user2InputArr=array("a","a","a","z","a","E","E","E","a","E");
我知道如何在两个数组中找到匹配的成员。在这里,我想找到具有相似索引的匹配元素,例如if $ userInputArr [4] == $ user2InputArr [4],增加$ matches。在我下面的尝试中,我遍历两个数组,但我不能让$ matchs增加。
$match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {
for ($d = $c; $d<count($user2InputArr);$d++) {
if ($userAnsStrArr[$c] == $userInputArr[$d]) {
$match = $match +1;
}
}
}
答案 0 :(得分:1)
这个问题是PHP函数array_intersect_assoc()
的完美示例:
$array1 = array("z","z","E","z","z","E","E","E","E","E");
$array2 = array("a","a","a","z","a","E","E","E","a","E");
// Find the matching pairs (key, value) in the two arrays
$common = array_intersect_assoc($array1, $array2);
// Print them for verification
print_r($common);
// Count them
$match = count($common);
echo($match." common items.\n");
输出结果为:
Array
(
[3] => z
[5] => E
[6] => E
[7] => E
[9] => E
)
5 common items.
答案 1 :(得分:0)
$match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {
if ($userAnsStrArr[$c] == $userInputArr[$c]) {
$match = $match +1;
}
}
你应该这样做。
答案 2 :(得分:0)
这对我有用
$i = sizeof($userInputArr);
$match = 0;
for($j = 0; $j < $i; $j++)
if ($userInputArr[$j] == $user2InputArr[$j]) {
$match = $match +1;
}
答案 3 :(得分:0)
这是给你的代码。只需使用一个foreach
,遍历第一个array
,然后检查第二个key-value
中的array
。
$s = array("z","z","E","z","z","E","E","E","E","E");
$b = array("a","a","a","z","a","E","E","E","a","E");
foreach($s as $k => $v) {
if($b[$k] === $s[$k]) {
echo $k . ' is the index where keys and values exactly match with value as ' . $b[$k];
}
}
输出:
3 is the index where keys and values exactly match with value as z
5 is the index where keys and values exactly match with value as E
6 is the index where keys and values exactly match with value as E
7 is the index where keys and values exactly match with value as E
9 is the index where keys and values exactly match with value as E
答案 4 :(得分:0)
我似乎你的代码在单循环中不需要两个for循环增加匹配,见下面的代码。
<?php
$userInputArr=array("z","z","E","z","z","E","E","E","E","E");
$user2InputArr=array("a","a","a","z","a","E","E","E","a","E");
$match = 0;
for ($c =0; $c < count($userInputArr); $c++) {
if ($user2InputArr[$c] == $userInputArr[$c]) {
$match = $match + 1;
}
}
echo $match;
?>