У меня есть два массива с одинаковым количеством членов (всегда)$userInputArr=array("z","z","E","z","z","E","E","E","E","E");
а также $user2InputArr=array("a","a","a","z","a","E","E","E","a","E");
Я знаю, как найти подходящих членов в двух массивах. Здесь я хочу найти подходящие элементы с похожими индексами, например, если $ userInputArr [4] == $ user2InputArr [4], приращение $ соответствует. В моей попытке ниже я перебираю оба массива, но не могу получить $ 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;
}
}
}
Этот вопрос является идеальным примером для функции 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.
$match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {
if ($userAnsStrArr[$c] == $userInputArr[$c]) {
$match = $match +1;
}
}
Вы должны сделать это так.
Это работает для меня
$i = sizeof($userInputArr);
$match = 0;
for($j = 0; $j < $i; $j++)
if ($userInputArr[$j] == $user2InputArr[$j]) {
$match = $match +1;
}
Вот код для вас. Просто используйте один 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
А вот и ссылка: https://3v4l.org/eX0r4
Мне кажется, ваш код не нуждается в двух для совпадения увеличения цикла в одном цикле, см. Код ниже.
<?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;
?>