在多个数组中搜索 [英] Search Multiple Arrays for

查看:83
本文介绍了在多个数组中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经正式碰壁,我无法找出解决该问题的方法.任何帮助将非常感激!我已经尝试过 array_intersect(),但是它只是针对第一个数组运行在该功能中,将无法正常工作.

I have officially hit a wall and I cannot figure out the solution to this issue. Any help would be much appreciated! I have tried array_intersect() but it just keeps running against the first array in the function, that wont work.

我有无限数量的数组(出于演示目的,我将显示4),例如:

I have an infinite amounts of arrays (I'll show 4 for demonstration purposes), for example:

// 1.
array(1,2,3,4,5);
// 2.
array(1,3,5);
// 3.
array(1,3,4,5);
// 4.
array(1,3,5,6,7,8,9);

我需要弄清楚如何搜索所有数组并仅查找所有4个数组中存在的数字.在此示例中,我只需要从数组中提取值-1、3&5.

I need to figure out how to search all the arrays and find only the numbers that exist in all 4 arrays. In this example I need to only pull out the values from the arrays - 1, 3 & 5.

PS:实际上,最好是该函数可以对多维数组进行搜索并仅提取与数组中所有数组匹配的数字.

PS: In all reality, it would be best if the function could search against a multi dimensional array and extract only the numbers that match in all the arrays within the array.

非常感谢您的帮助!

推荐答案

有趣的问题!这可行:

function arrayCommonFind($multiArray) {

    $result = $multiArray[0];
    $count = count($multiArray);
    for($i=1; $i<$count; $i++) {
        foreach($result as $key => $val) {
            if (!in_array($val, $multiArray[$i])) {
                unset($result[$key]);
            }
        }
    }
    return $result;
}

请注意,您只能使用$ multiArray [0](或 any 子数组)作为基准,并对照所有其他基准进行检查,因为最终结果中的任何值都必须在所有单独的子数组中.

Note that you can just use $multiArray[0] (or any sub-array) as a baseline and check all the others against that since any values that will be in the final result must necessarily be in all individual subarrays.

这篇关于在多个数组中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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