如何获得多维数组的交集? [英] How to get the intersection of an array of multidimensional arrays?

查看:179
本文介绍了如何获得多维数组的交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组的数组.每个数组代表搜索的结果集.我试图弄清楚如何过滤这组数据,使其仅包括每个数组中存在的数组.

I have an array of multidimentional arrays. Each array represents a result set from a search. I am having trying to figure out how to filter this set of data to only include arrays that are present in each array.

注:下方显示的索引分别表示多维数组.每个数组都有一个深层嵌套的Id键,可用于比较.

Note: The index's shown below each represent multidimentional arrays. Each array has a deeply nested Id key that can be used for comparison.

Id位于:

$reference_variable['data']['Id'][0]

例如

array(
    array([0], [19], [21], [148]),
    array([2], [21], [32], [44], [432], [549]),
    array([13], [21], [148])
)

应返回:

array(
    [21]
)

和:

array(
    array([0], [12], [15]),
    array([2], [21], [32], [44], [432], [549]),
    array([13], [21], [148])
)

应返回:

array(
    []
)

处理此问题的最佳方法是什么? array_intersect 在多维数组上无法很好地工作.

What is the best way to handle this? array_intersect does not work well with multidimensional arrays.

我已经尝试将所有Id存储在数组中,并使用array_count_values查找重复的Id s,然后使用array_filter比较当前数组的Id是否相等到任何重复的Id.

I've already tried storing all Ids in an array, and using array_count_values to find duplicate Ids, and then use array_filter to compare if the Id of the current array was equal to any of the duplicate Id's.

但是事实证明这是完全错误的,因为此方法将允许:

But that turned out to be totally wrong since this method would allow:

array(
    array([0], [19], [21], [148]),
    array([2], [21], [32], [44], [432], [549]),
    array([13], [21], [148])
)

要返回:

array(
    [21, 148]
)

不是所有数组的交集.

推荐答案

这是我的答案:

$params = array_merge($array_of_arrays, array('array_compare'));

$intersection = call_user_func_array('array_uintersect', $params);

function array_compare($a1, $a2) 
{
    if ($a1 === $a2) {
        return 0;
    }
    if ($a1 > $a2) {
        return 1;
    }
    return -1;
}

信用: https://stackoverflow.com/a/2020654/1911755

这篇关于如何获得多维数组的交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆