2014-03-30 79 views
0

如果我有兩個數組的陣列如何計算兩個數組中單詞的出現次數? (使用php)

D [0] = array(「I」,「want」,「to」,「make」,「cake」,「and」,「 D「[1] =數組(」姐妹「,」想要「,」到「,」需要「,」該「,」蛋糕「,」那個「,」我「,」製造「 「)
如何計算兩個數組中單詞的出現次數?

例如輸出:
word |數組[0] | array [1]
I:1 | 1
想要1 | 1
發送至:1 | 1
make:2 | 0
cake:1 | 1
和:1 | 0
juice:1 | 0
sister:0 | 1
需要:0 | 1
the:0 | 1
that:0 | 1
設爲:0 | 1

回答

0

你可以用array_count_values()

$count[0] = array_count_values($D[0]); //Assuming you meant to have D as a variable in your question 
$count[1] = array_count_values($D[1]); 

的關鍵是單詞,值是多少。

1

該解決方案構建了一個包含全部字的數組,該數組稍後用於兩個查找數組$ d [0]和$ d 1的迭代 。 array_unique(array_merge())例如刪除重複的「make」。

array_count_values()用於計數值。

最後,爲了顯示錶格,allwords數組作爲迭代器。

對於每個單詞新行id,word,calc from array1,calc from array2

長話短說。這裏的

PHP

<?php 

$d = array(); 
$d[0] = array("I", "want", "to", "make", "cake", "and", "make", "juice"); 
$d[1] = array("Sister", "want", "to", "takes", "the", "cake", "that", "i", "made"); 

$allwords = array_unique(array_merge($d[0], $d[1])); 

echo '<table>'; 
echo '<thead><th>Word ID</th><th>Word</th><th>Array 1</th><th>Array 2</th></thead>'; 

$array1 = array_count_values($d[0]); 
$array2 = array_count_values($d[1]); 

foreach($allwords as $id => $word) { 
    echo '<tr><td>'. $id . '</td><td>' . $word . '</td>'; 

    if(isset($array1[$word])) { 
     echo '<td>' . $array1[$word] . '</td>'; 
    } else { 
     echo '<td>0</td>'; 
    } 

    if(isset($array2[$word])) { 
     echo '<td>' . $array2[$word] . '</td>'; 
    } else { 
     echo '<td>0</td>'; 
    } 
} 

echo '</table>'; 

結果

enter image description here

相關問題