简体   繁体   English

比较两个数组以找到相同的值

[英]Compare two arrays to find their same values

Here is two numeric array: 这是两个数值数组:

$a = array(0 => '1,3');

$b = array(
    0 => '1,2,4',
    1 => '1,2',
    2 => '4,3',
    3 => '2,4',
    4 => '1,3'
);

I want to compare these two arrays and find their same values. 我想比较这两个数组并找到它们相同的值。 For example, in this case [0] => 1,3 in the first array is matching with [4] => 1,3 in the second one. 例如,在这种情况下,第一个数组中的[0] => 1,3与第二个数组中的[4] => 1,3匹配。

I tried to achieve this by using array_diff but with no success. 我试图通过使用array_diff实现此目标,但没有成功。 Can any one help this out? 有人可以帮忙吗?

Use array_search() to search within array a given value: 使用array_search()在数组中搜索给定值:

$a = array(0 => '1,3');
$b = array(
    0 => '1,2,4',
    1 => '1,2',
    2 => '4,3',
    3 => '2,4',
    4 => '1,3'
);

foreach ($a as $val) {
    if ($key = array_search($val, $b)) {
        echo "'$val' is matched in '$key' index";
        break;
    }
}

Output: 输出:

'1,3' is matched in '4' index

You can also do the following: 您还可以执行以下操作:

$match = array();
foreach ($a as $val) {
    if (array_search($val, $b)) {
        $match[] = $val;
    }
}

print_r($match);

Output: 输出:

Array
(
    [0] => 1,3
)

Update: 更新:

As the OP mentioned, for this purpose we use array_intersect() function as well: 正如OP所述,为此,我们还使用array_intersect()函数:

$a = array(0 => '1,3');
$b = array(
    0 => '1,2,4',
    1 => '1,2',
    2 => '4,3',
    3 => '2,4',
    4 => '1,3'
);

print_r(array_intersect($a, $b));

Output: 输出:

Array
(
    [0] => 1,3
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM