John Davidson

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

0 comments
Message:


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);


My Answer:
1, 'userid' => 123, 'name' => 'John'],
['id' => 2, 'userid' => 456, 'name' => 'Jane'],
['id' => 3, 'userid' => 789, 'name' => 'Alice']
];

$mongodb = [
['id' => 4, 'userid' => 123, 'email' => '[email protected]'],
['id' => 5, 'userid' => 456, 'email' => '[email protected]'],
['id' => 6, 'userid' => 999, 'email' => '[email protected]']
];

$matchedRecords = [];

foreach ($mysql as $mysqlRow) {
foreach ($mongodb as $mongodbRow) {
if ($mysqlRow['userid'] == $mongodbRow['userid']) {
$matchedRecords[] = $mongodbRow;
}
}
}

print_r($matchedRecords);

Rate this post

3 of 5 based on 6251 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us