Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

php - array_intersect() with dynamic length of arguments

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...