2017-08-14 23 views
0

我有两个数组有相同数目的成员(总是)的$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],则增加$匹配。在我下面的尝试中,我通过两个数组循环,但我无法获得$匹配增量。比较两个数组中的元素,在同类指标相互

$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

“foreach”会不会更适合? – Script47

+0

@ Script47我也尝试了一个foreach循环,没有成功 – jimiss

+0

在这里嵌套两个循环是无稽之谈。你想循环访问数组中的_one_,并在访问另一个数组时访问对应的元素。 – CBroe

回答

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. 
+0

因此,减免在臃肿的页面上看到明智的答案。没有知情的PHP开发人员会做任何事情,除此之外! – mickmackusa

0
$match = 0; 
for ($c =0; $c < count($$userInputArr); $c++) { 

    if ($userAnsStrArr[$c] == $userInputArr[$c]) { 
      $match = $match +1; 
     } 

} 

你应该做的是这样的。

+0

'count($$ userInputArr)'上有一个输入错误,它阻止了它的工作。此外,我会迭代,直到两个数组的较小长度,以避免在第二个数组比第一个数组短时触发通知。 – axiac

0

这对我的作品

$i = sizeof($userInputArr); 

$match = 0; 
for($j = 0; $j < $i; $j++) 
    if ($userInputArr[$j] == $user2InputArr[$j]) { 
     $match = $match +1; 
    } 
+1

'sizeof'可能会与别的东西混淆,所以最好使用'count'。 – Script47

+0

我将'$ i'设置为两个数组的较小长度,以避免在第二个数组比第一个数组短的情况下触发通知。 – axiac

+0

在这种情况下“我有两个成员数相同的数组(总是)”。我简化了它。我是新的在stackoverflow。 –

0

下面是代码您。只需使用一个foreach,穿越的第一array,并且在第二array检查为key-value

$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

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; 
?> 
相关问题