我想在php中比较和合并数组。假设我有两个数组如下
$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'));
我想合并上面两个数组,以便我将为这些国家/地区设置唯一的值,如果数组中有重复的国家/地区,则应添加其他三个字段的值并将其合并。
尝试以下代码 - 但我对逻辑感到困惑。
$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/>";
}
答案 0 :(得分:2)
我以不同的方式尝试了你的答案,并得到了你想要的东西。
$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'));
$collection = array();
foreach ($topCountries1 as $tc1) {
foreach($topCountries2 as $tc2){
if(in_array($tc1[0], $tc2)){
$collect[0] = $tc1[0];
$collect[1] = $tc1[1] + $tc2[1];
$collect[2] = $tc1[2] + $tc2[2];
$collect[3] = $tc1[3] + $tc2[3];
array_push($collection, $collect);
}
}
}
$final_array = $collection;
foreach($topCountries1 as $tc1){
$flag = true;
foreach($collection as $coll){
if(in_array($tc1[0], $coll)){
$flag = false;
break;
}
}
if($flag){
array_push($final_array, $tc1);
}
}
foreach($topCountries2 as $tc1){
$flag = true;
foreach($collection as $coll){
if(in_array($tc1[0], $coll)){
$flag = false;
break;
}
}
if($flag){
array_push($final_array, $tc1);
}
}
var_dump($final_array);
array_merge将合并它想要添加数据的数据
答案 1 :(得分:2)
你可以通过简单地保持一个由你想要合并的键组织的全局数组来实现它,你可以避免使用O(n²)复杂度,只需简单的O(n)假设哈希查找为关键是O(1)。
这是一个比之前发布的解决方案更简单的解决方案,并且无需添加更多代码即可接受任意数量的输入数组,此外还允许您在国家/地区名称后面扩展值的数量,而无需添加更多代码。
$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',
),
);
$countries = array();
$data = array($topCountries1, $topCountries2);
foreach($data as $entries)
{
foreach($entries as $country)
{
$name = $country[0];
// if first time we see the country, add it to the list
if (!isset($countries[$name]))
{
$countries[$name] = $country;
}
else
{
// add all fields after the first (the name)
foreach (array_slice($country, 1, null, true) as $idx => $value)
{
$countries[$name][$idx] += $value;
}
}
}
}
var_dump($countries);
var_dump(array_values($countries));
希望有所帮助!