array_intersect() 具有参数的动态长度 [英] array_intersect() with dynamic length of arguments

查看:43
本文介绍了array_intersect() 具有参数的动态长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,当脚本运行时,这些数组的元素数可能不同.

I've got an array of arrays that may have a different count of elements when the script is run.

$strict = [
    [0] => ['one', 'two', 'three', 'four'],
    [1] => ['one', 'two', 'four', 'eight'],
    [2] => ['two', 'four', 'ten', 'twenty'],
 /* [x] => [. . .] */
];

$result = array_intersect($strict[0], $strict[1], $strict[2]);
print_r($result); //shows ['two', 'four'];

我想做这样的事情:

$result = array_intersect($strict);

我传入一个动态长度的数组数组,array_intersect 将遍历每个数组并只获取公共条目.

Where I pass in a dynamic length array of arrays and array_intersect will go through each one and take only the common entries.

执行array_intersect($strict) 不起作用,因为该函数至少需要两个参数.

Doing array_intersect($strict) does not work, because the function requires at least two arguments.

也许类似

array_intersect(function ($array) {
    $list = '';
    foreach ($array as $el) {
        $list .= $el.',';
    }

    $list = rtrim($list, ',');

    return eval($list);
});

虽然这个特定的方法仍然抛出错误

though this particular method still throws the error

警告:array_intersect():至少需要2个参数,1给定

Warning: array_intersect(): at least 2 parameters are required, 1 given

推荐答案

您可以使用 call_user_func_array:

You can use call_user_func_array:

使用参数数组调用回调

所以你的回调是array_intersect,你可以像这样传递你的数组:

So your callback would be array_intersect, and you could pass your array like this:

$result = call_user_func_array('array_intersect', $strict);

这篇关于array_intersect() 具有参数的动态长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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