I am trying to Compare and merge arrays in php. Lets say i have two arrays as follows
$topCountries1 = array(
array(
'India',
'23',
'34',
'11'),
array(
'USA',
'13',
'24',
'21'),
array(
'Japan',
'13',
'24',
'21'));
$topCountries2 = array(
array(
'France',
'23',
'34',
'11'),
array(
'India',
'13',
'24',
'21'),
array(
'Japan',
'13',
'24',
'21'));
I want to merge the above two arrays so that i will have unique set of values for the countries and if there are duplicate countries in the array it should add the values of the other three fields and combine it.
Trying out the following code – but i am confused with the logic.
$topCountries = array_merge($topCountries1, $topCountries2);
$collect = array();
foreach ($topCountries as $tc) {
echo $count = count($collect);
if ($count > 0) {
foreach ($collect as $c) {
if ($c[0] == $tc[0]) {
echo "match<br/>";
$collect[] = $tc;
} else {
$collect[] = $tc;
echo "no match<br/>";
}
}
} else {
$collect[] = $tc;
}
echo "<br/>";
}
You can do it by simply keeping a global array organized by the key you want to merge, and you’ll avoid having to do it with O(n²) complexity, just simple O(n) assuming that the hash lookup for the key is O(1).
This is a simpler solution than the one previously posted and accepts an arbitrary number of input arrays without having to add more code, in addition to allowing you to expand the number of values after the country name without having to add more code.
Hope that helps!