phpmultidimensional-arrayfilteringarray-differencearray-intersect

Compare two 2d arrays & get intersection and differences


I want to compare the data in whole rows between the two arrays and produce:

I have two multidimensional arrays with me.

$array1 = [
    ['sight_id' => 13, 'location' => 'Jodhpur, Rajasthan, India'],
    ['sight_id' => 14, 'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India'],
    ['sight_id' => 15, 'location' => 'D-Kirtinagar, Jodhpur, Rajasthan, India'],
];

$array2 = [
    ['sight_id' => 13, 'location' => 'Jodhpur, Rajasthan, India'],
    ['sight_id' => 14, 'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India'],
    ['sight_id' => 16, 'location' => 'Jaisalmer, Rajasthan, India'],
    ['sight_id' => 17, 'location' => 'Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India'],
];

Desired results:

$intersect_array = [
    ['sight_id' => 13, 'location' => 'Jodhpur, Rajasthan, India'],
    ['sight_id' => 14, 'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India'],

and

$only_a1 = [
    ['sight_id' => 15, 'location' => 'D-Kirtinagar, Jodhpur, Rajasthan, India'],
]

and

$only_a2 = [
    ['sight_id' => 16, 'location' => 'Jaisalmer, Rajasthan, India'],
    ['sight_id' => 17, 'location' => 'Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India'],
];

Solution

  • Convert arrays to a format, where array index is the sight_id:

    $b1 =array();
    foreach($a1 as $x)
        $b1[$x['sight_id']] = $x['location'];
    
    $b2 =array();
    foreach($a2 as $x)
        $b2[$x['sight_id']] = $x['location'];
    

    Calculate the differences and intersection:

    $c_intersect = array_intersect_key($b1,$b2);
    $c_1 = array_diff_key($b1,$b2);
    $c_2 = array_diff_key($b2,$b1);
    

    Convert arrays back to your format:

    $intersect_array = array();
    foreach($c_intersect as $i=>$v)
        $intersect_array[] = array('sight_id'=>$i,'location'=>$v);
    
    $only_a1 = array();
    foreach($c_1 as $i=>$v)
        $only_a1[] = array('sight_id'=>$i,'location'=>$v);
    
    $only_a2 = array();
    foreach($c_2 as $i=>$v)
        $only_a2[] = array('sight_id'=>$i,'location'=>$v);