array_intersect a variable amount of arrays

天大地大妈咪最大 提交于 2019-12-01 05:04:18

问题


I am creating a faceted search, and I'm am trying to use array_intersect to compare the arrays and find the inputs that match.

The problem is that I will have a variable amount of arrays at anytime depending on what filters the user has selected:

$array_1, $array_2, $array_3 etc...

How do I create an array_intersect function that is dynamic in this sense?

This is what I've tried:

$next_array = 0;
for($i = 0; $i < $array_count; $i++) {
    $next_array++;
    if ($i == 0) {
        $full_array = ${array_.$i};
    } else {
        if(!empty(${cvp_array.$next_array})) {
            $full_array = array_intersect($full_array, ${cvp_array_.$next_array});
        }
    }
}

------------- EDIT -------------

I'll try to narrow down my goal a bit more:

If the user clicks three filters, this results in three arrays being created with each having individual results:

Array_1 ( [0] => 2, [1] => 4, [2] => 6 )

Array_2 ( [0] => 1, [1] => 4, [2] => 6 )

Array_3 ( [0] => 6, [1] => 7, [2] => 8 )

I need code that will find the number that is in ALL of the arrays. And if there is no common number then it would end as false or something. In the case above, I'd need it to retrieve 6. If it was only the first two arrays, it would return 4 and 6.


回答1:


First of all, turn those arrays into an array of arrays. Then you can use array_reduce combined with array_intersect to reduce a variable amount of arrays down to one.




回答2:


Try this:

$fullArray = array($array1, $array2, $array3...);
call_user_func_array('array_intersect', $fullArray);



回答3:


You can turn those array to a single array named $total_array by using array_combine(), then use array_intersect($full_array, $total_array). I hope this useful




回答4:


One can use:

$intersect = array_intersect(...$fullArray);


来源:https://stackoverflow.com/questions/12381085/array-intersect-a-variable-amount-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!