如何计算两个数组中出现的单词? (用php)

if I have an array of two arrays

D[0] = array ("I", "want", "to", "make", "cake", "and", "make", "juice")
D[1] = array ("Sister", "want", "to", "takes", "the", "cake", "that", "i", "made")
how to count the occurrences of words that are in both arrays?

eg output:
word | array[0] | array[1]
I : 1 | 1
want : 1 | 1
to : 1 | 1
make : 2 | 0
cake : 1 | 1
and : 1 | 0
juice : 1 | 0
sister : 0 | 1
takes : 0 | 1
the : 0 |1
that : 0 | 1
made : 0 | 1

You can just use 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]);

The key is the word and the value is the number.

This solution builds an array with allwords, which is later used for iteration of the two lookup arrays $d[0] and $d1. array_unique(array_merge()) to delete duplicate "make" for instance.

The array_count_values() is used for the counting of values.

Finally, for displaying the table, the allwords array is as iterator.

For each word a new row with id, word, calc from array1, calc from array2.

Long story, short. Here's the

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>';

Result

enter image description here