查找数组数组中的共同值

问题描述 投票:0回答:5

我有一个数组的数组。

$a = [
    [1, 2, 3],
    [2, 3, 4],
    [2, 4, 5]
];

如何找到所有数组中存在的共同元素?

在上面的示例数据中,我希望有一个包含值

2
的结果数组,因为它是所有行中出现的唯一值。

php arrays multidimensional-array filtering intersection
5个回答
4
投票

这是我做的一个功能。它只是多维数组的参考。

<?php
$array1 = array('angka'=>12,'satu','2'=>'dua','tiga'=>array('dua','enam','empat'=>array('satu','lima',12)));//object
$array2 = array('dua','tiga','empat',12);//object as intersect refference

function intersect($data=NULL)
{
    if(!empty($data))
    {
        $crashed = array();
        $crashed2 = array();
        foreach($data[0] as $key=>$val)
        {
            if(!is_array($val))
            {
                $crashed[$key] = in_array($val,$data[1]);//return true if crashed (intersect)
            }
            else
            {
                $crashed2[$key] = intersect(array($val,$data[1]));
            }
            $crashed = array_merge($crashed,$crashed2);
        }
    }
    return $crashed;
}
$intersect = intersect(array($array1,$array2));
print_r($intersect);
?>

它返回这样的结果:

Array ( [angka] => 1 [0] => [1] => 1 [tiga] => Array ( [0] => 1 [1] => [empat] => Array ( [0] => [1] => [2] => 1 ) ) ) 

如果数组的值与引用数组匹配,则返回 true。

希望代码能帮到你。


2
投票

看看这里

array-intersect
。 你可以这样使用它:

$intersect = $a[0];
for ($i = 1; $i < count($a); $i++)
{
    $intersect = array_intersect($intersect, $a[$i]);
}

1
投票

您可以通过以下方式避免 foreach 循环

call_user_func_array('array_intersect',$a);

0
投票

顾名思义,我认为你可以使用 array-intersect

从该页面:

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

给予

Array
(
    [a] => green
    [0] => red
)

0
投票

将行解压到单个

array_intersect()
调用中以确定所有行中出现的值。 结果将保留数组第一行中合格值的键。

代码:(演示

$array = [
    [1, 2, 3, 4],
    [2, 3, 4, 5],
    [3, 4, 5, 6]
];

var_export(array_intersect(...$array));

输出:

array (
  2 => 3,
  3 => 4,
)
© www.soinside.com 2019 - 2024. All rights reserved.