2014-03-30 77 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

相关问题