Intersect unknown number of arrays in PHP

后端 未结 5 449
猫巷女王i
猫巷女王i 2021-01-11 09:30

I\'m trying to intersect an arbitrary number of PHP arrays, the count of which depends on a user provided parameter, each of which can have any number of elements.

F

相关标签:
5条回答
  • 2021-01-11 10:08
    $arrays = [
        $userArray1,
        $userArray2,
        $userArray3
    ];
    $result = array_intersect(...$arrays);
    
    0 讨论(0)
  • 2021-01-11 10:11

    I am posting my answer very very late, but just want to share a small piece of code that helps me ,in case somebody needs it for this question.

    print_r(array_intersect(array_merge($array1,$array2,...),$intersectionArr);
    

    I hope this helps

    Thanks

    0 讨论(0)
  • 2021-01-11 10:13

    Use the splat operator (...) as in: array_intersect(...$arrayOfArrays) or interchangeably call_user_func_array.

    It's in the code in this tutorial: https://www.youtube.com/watch?v=AMlvtgT3t4E

    0 讨论(0)
  • 2021-01-11 10:18

    Don't use eval()!

    Try this

    $isect = array();
    for ($i = 1; $i <= $N; $i++) {
        $isect = array_intersect($isect, ${'array'.$i});
    }
    

    or that

    $arrays = array()
    for ($i = 1; $i <= $N; $i++) {
        $arrays[] = ${'array'.$i};
    }
    $isect = call_user_func_array('array_intersect', $arrays);
    
    0 讨论(0)
  • 2021-01-11 10:27

    Create a new empty array, add each of your arrays to that, then use call_user_func_array()

    $wrkArray = array( $userArray1,
                       $userArray2,
                       $userArray3
                     );
    $result = call_user_func_array('array_intersect',$wrkArray);
    
    0 讨论(0)
提交回复
热议问题