2017-08-14 18 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; 
?> 
相關問題