2

我有:

阵列1:([0] => "Lion 1" [1] => "Cat 1" [2] => "Tiger 1" [3] => "Leopard 1")

数组2:([0] => "Lion 2" [1] => "Dog 2" [2] => "Tiger 2" [3] => "Leopard 2")

要显示的输出:

            Array1    |   Array2
            ++++++++++++++++++++
            Lion 1    |   Lion 2
            Cat 1     |   ______ <-Blank row
            Tiger 1   |   Tiger 2
            Leopard 1 |   Leopard 2
Blank row -> _______   |   Dog 2
4

2 回答 2

1

以下是一些可能对您有所帮助的代码:

<pre>
<?php
$array1 = Array("Lion 1", "Cat 1", "Tiger 1", "Leopard 1");
$array2 = Array("Lion 2", "Dog 2", "Tiger 2", "Leopard 2");

function build_map($array) {
    $map = Array();

    foreach($array as $val) {
        $parts = explode(' ', $val);
        $map[$parts[0]] = $val;
    }

    return $map;
}

$map1 = build_map($array1);
$map2 = build_map($array2);

$only1 = array_diff_key($map1, $map2);
$only2 = array_diff_key($map2, $map1);
$both = array_intersect_key($map1, $map2);

foreach($both as $key => $val)
    echo $map1[$key]."\t\t".$map2[$key]."\n";

foreach($only1 as $key => $val)
    echo "$val\t\t________\n";

foreach($only2 as $key => $val)
    echo "________\t\t$val\n";

?>
</pre>

它的输出如下。

Lion 1      Lion 2
Tiger 1     Tiger 2
Leopard 1       Leopard 2
Cat 1       ________
________        Dog 2

只要您在每个阵列中都有一种动物,这应该可行。

于 2012-10-15T03:57:05.427 回答
1

查看str_word_countarray_uniquearray_intersect了解更多详情。

您可以像这样使用它们:

$array1 = Array(0 => "Lion 1", 1 => "Cat 1", 2 => "Tiger 1", 3 => "Leopard 1");
$array2 = Array(0 => "Lion 2", 1 => "Dog 2", 2 => "Tiger 2", 3 => "Leopard 2");

$animals1 = array_unique(str_word_count(implode(' ', $array1), 1));
$animals2 = array_unique(str_word_count(implode(' ', $array2), 1));

# Compare the two arrays.
$intersect = array_intersect($animals1, $animals2);

# Check if there's a match.
if (count($intersect)) {
   # found a match
}
于 2012-10-15T04:25:45.453 回答