phparraysmultidimensional-arrayfilteringarray-intersect

Filter out rows of a 2d array if the row is not found in another 2d array


I've written this code:

$aArray = [
    [0, 0, 0], 
    [1, 0, 0], 
    [2, 0, 0], 
    [3, 0, 0], 
    [4, 0, 0], 
    [5, 0, 0], 
    [6, 0, 0], 
    [7, 0, 0], 
];

$jump = [
    [0, 0, 0], 
    [1, 0, 0], 
    [9, 7, 4], 
    [3, 0, 0], 
    [4, 0, 0], 
    [5, 0, 0], 
    [6, 0, 0], 
    [7, 0, 0], 
];
var_dump(array_intersect($aArray, $jump));

the result I'm getting is this:

array(8) { 
[0]=> array(3) { 
    [0]=> int(0) 
    [1]=> int(0) 
    [2]=> int(0) } 
[1]=> array(3) { 
    [0]=> int(1) 
    [1]=> int(0) 
    [2]=> int(0) } 
[2]=> array(3) { 
    [0]=> int(2) 
    [1]=> int(0) 
    [2]=> int(0) } 
[3]=> array(3) { 
    [0]=> int(3) 
    [1]=> int(0) 
    [2]=> int(0) } 
[4]=> array(3) { 
    [0]=> int(4) 
    [1]=> int(0) 
    [2]=> int(0) } 
[5]=> array(3) { 
    [0]=> int(5) 
    [1]=> int(0) 
    [2]=> int(0) } 
[6]=> array(3) { 
    [0]=> int(6) 
    [1]=> int(0) 
    [2]=> int(0) } 
[7]=> array(3) { 
    [0]=> int(7) 
    [1]=> int(0) 
    [2]=> int(0) } 
    }

Why isn't the second index getting filtered out? I've tried emptying my cache in case it had old values stored in there. I've also noticed that if I delete the last array from the jump array, it still produces 7,0,0. Is this a weird anomaly?


Solution

  • array_intersect() is not recursive, it sees the inner arrays as just an array. You would need to use something like this:

    function array_intersect_recursive() {
    
        foreach(func_get_args() as $arg) {
            $args[] = array_map('serialize', $arg);
        }
        $result = call_user_func_array('array_intersect', $args);
    
        return array_map('unserialize', $result);
    }
    
    $result = array_intersect_recursive($aArray, $jump);