具有动态参数长度的array_intersect()

Nal*_*roc 2 php arrays dynamic

我有一个数组数组,当运行脚本时,该数组的元素数可能会有所不同。

$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'];
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

$result = array_intersect($strict);
Run Code Online (Sandbox Code Playgroud)

我在其中传递了一个动态长度的数组,并且array_intersect将遍历每个数组并仅接受公共条目。

这样做array_intersect($strict)不起作用,因为该函数至少需要两个参数。

也许像

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

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

    return eval($list);
});
Run Code Online (Sandbox Code Playgroud)

尽管此特定方法仍然会引发错误

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

tri*_*cot 5

您可以使用call_user_func_array

调用带有参数数组的回调

因此您的回调将为array_intersect,您可以像这样传递数组:

$result = call_user_func_array('array_intersect', $strict);
Run Code Online (Sandbox Code Playgroud)