phparraysmultidimensional-arrayintersectioncounting

Count the number of value intersections between a 3d array and a flat array


I have two arrays:

$array1 = [
    [['host' => 'test1']],
    [['host' => 'test2']],
];

$array2 = [
    'test1',
    'ghfhfghfg',
];

Now I want to compare these arrays and return $nCount = 1 because test1 exists in both tables.


Solution

  • First of all you have to know what's your input. In your case I assumed that you will always have the same type of multi-column "table" (as you call it).

    For this case you can use something like the following which flattens the multi-column array to a flat array like the second one.

    <?php
    $multi_col = array(
        array(
            array(
                'host'=>'test1'
            )
        ),
        array(
            array(
                'host'=>'test2'
            )
        )
    );
    
    $single_col = array('test1', 'sfsd');
    $single_cold_multicol = array_map(function(Array $item){
        return $item[0]['host'];
    }, $multi_col);
    
    $diff_compare = array_diff($single_col, $single_cold_multicol);
    $nCount = count($single_col) - count($diff_compare);
    

    In case youre $multi_col does not always have the same depth, you would need to recursively flatten. If it does always have the same depth (you always know how the array is built), you can just use the code above.