Search code examples
phparraysmultidimensional-arrayfilteringintersection

Find intersections between the subset values of each rows of a multidimensional array versus another flat associative array


I have two arrays $firstarray and $secondarray as below:

$firstarray = [
    [
        'id' => 1.25,
        'Name' => 'rose',
        'Number' => 15,
        'DOB' => [
            [
                'Day' => 13,
                'Month' => 5,
                'Year' => 1993
            ]
        ],
        'SSN' => [12345, 3455]
    ],
    [
        'id' => 1.15,
        'Name' => 'orchid',
        'Number' => 7,
        'DOB' => [
            [
                'Day' => 3,
                'Month' => 7,
                'Year' => 1912
            ]
        ],
        'SSN' => [12363, 3465]
    ],
];

and

$secondarray = ['Day' => 13, 'Month' => 5, 'Year' => 1993];

I want to filter the first array by comparing the DOB data against the second array data.

foreach ( $firstarray as $item ) {
    print_r(array_intersect_assoc( $secondarray, $item ); 
}

My problem is that the two arrays should intersect only on the first iteration, but my code is intersecting on all iterations. I think it is only intersecting keys i.e day,month,year. How can I check whether values are also matched?


Solution

  • Is this what you are looking for

    $result = array();
    foreach ( $firstarray as $item ) {
        $instersectArray=array_intersect_assoc($secondarray,$item['DOB'][0]);
        if($instersectArray){
            $result[] = $item;
        }
    }
    print_r($result);
    

    Check Demo

    If you need only one match

    $result = array();
    foreach ( $firstarray as $item ) {
        $instersectArray=array_intersect_assoc($secondarray,$item['DOB'][0]);
        if($instersectArray && empty($result)){
            $result[] = $item;
        }
    }
    print_r($result);
    

    Check Demo