doumeng3345
2017-04-30 20:24
浏览 89
已采纳

具有动态参数长度的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'];

I want to do something like this though:

$result = array_intersect($strict);

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

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

Maybe something like

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

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

图片转代码服务由CSDN问答提供 功能建议

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

  $ 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);  //显示['two','four']; 
   
 
 

我想做类似这样的事情:

   $ result = array_intersect($ strict); 
   
 
 

我传入一个动态长度的数组数组,而 array_intersect 将会去 通过每一个,只采取共同的条目。

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

可能像

  array_intersect(function($ array){
 $ list =''; 
 foreach($ array) 如$ el){
 $ list。= $ el。','; 
} 
 
 $ list = rtrim($ list,','); 
 
返回eval($ list); \  n}); 
   
 
 

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanhe8280 2017-04-30 20:35
    已采纳

    You can use call_user_func_array:

    Call a callback with an array of parameters

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

    $result = call_user_func_array('array_intersect', $strict);
    
    打赏 评论
  • douhuang9886 2017-04-30 20:52

    You can take advantage of modern PHP's array packing/unpacking features - aka variadics, or the so-called "splat" (...) operator - as well:

    $result = array_intersect(...$strict);
    
    打赏 评论

相关推荐 更多相似问题