Skip to content
Advertisement

Compare 2 arrays containing rows of data and displays the matched records

I am trying to figure out a way that I could match the ‘userid’ on both arrays. Then the ones that match, keep the rows in MongoDBResults.

$mysql = [
    ['id' => 1, 'userid' => 655342],
    ['id' => 3, 'userid' => 777777],
    ['id' => 6, 'userid' => 454777],
];

$mongo = [
    ['id' => 1, 'userid' => 655342, 'addr1' => '123 Test Ave', 'addr2' => 'MyCityState', 'zipcd' => '99955', 'items' => 888888],
    ['id' => 2, 'userid' => 989855, 'addr1' => '124 Test Ave', 'addr2' => 'MyCityState', 'zipcd' => '66955', 'items' => 887788],
    ['id' => 3, 'userid' => 777777, 'addr1' => '125 Test Ave', 'addr2' => 'MyCityState', 'zipcd' => '11955', 'items' => 886688],
    ['id' => 4, 'userid' => 666666, 'addr1' => '126 Test Ave', 'addr2' => 'MyCityState', 'zipcd' => '39954', 'items' => 885588],
];

Desired output:

array (
  0 => 
  array (
    'id' => 1,
    'userid' => 655342,
    'addr1' => '123 Test Ave',
    'addr2' => 'MyCityState',
    'zipcd' => '99955',
    'items' => 888888,
  ),
  2 => 
  array (
    'id' => 3,
    'userid' => 777777,
    'addr1' => '125 Test Ave',
    'addr2' => 'MyCityState',
    'zipcd' => '11955',
    'items' => 886688,
  ),
)

I tried:

$results = array_intersect($mysql, $mongo);

also

$result = array_diff($mysql, $mongo);

Advertisement

Answer

You can index on userid and then compute the intersection of the keys:

$results = array_intersect_key(array_column($MongoDBResults, null, 'userid'),
                               array_column($MySqlResults, null, 'userid'));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement