在 PHP 中,如何将特定键匹配的 2 个数组的值加在一起?

In PHP, how do I add values together from 2 arrays where specific keys match?

我找到了这篇文章 (How in PHP to add values from one array to another when their key value pairs match?),其中解释了与我正在尝试执行的操作类似但略有不同的操作。

这是我的两个数组:

$array1 =( 
    [0] => Array ( [count] => 2 [time] => 12 [location] => 1041)
    [1] => Array ( [count] => 5 [time] => 5 [location] => 1700)
    [2] => Array ( [count] => 3 [time] => 10 [location] => 1500));

$array2 =( 
    [0] => Array ( [count] => 1 [time] => 12 [location] => 1041)
    [1] => Array ( [count] => 5 [time] => 5 [location] => 1700)
    [2] => Array ( [count] => 6 [time] => 10 [location] => 1500));

我想构建一个新数组,其中 $array1$array2[count] 值相加在一起,其中键 [time][location] 来自 $array1$array2 匹配。

这就是我希望的输出方式:

$compositeArray =(
    [0] => Array ( [count] => 3 [time] => 12 [location] => 1041)
    [1] => Array ( [count] => 10 [time] => 5 [location] => 1700)
    [2] => Array ( [count] => 9 [time] => 10 [location] => 1500));

谢谢!

建立对您链接到的问题的公认答案:

foreach($array1 as $key1=>$value1)
{
  foreach($array2 as $key2=>$value2)
  {
    if($value1['time']==$value2['time'] && $value1['location']==$value2['location'])
    {
      $value1['count'] += $value2['count'];
      $result[$key1][]=$value1;
    }
  }
}

print_r($result);

一个简单的方法(没有嵌套循环)是遍历[=​​11=],检查并查看如果 $array2 中存在相同的键(假设它们已经按顺序组织)并在计算发生后创建一个新的数据数组。

foreach($array1 as $key => $value)
{
    if( array_key_exists($key, $array2) && $value['time'] == $array2[$key]['time'] && $value['location'] == $array2[$key]['location'] )
    {
        $result[] = array(
            'count'    => $value['count'] + $array2[$key]['count'],
            'time'     => $value['time'],
            'location' => $value['location']
        );
    }
}

print_r($result);
try this:

$result = array();
foreach($array1 as $key1=>$value1)
{
    foreach($array2 as $key2=>$value2)
  {
        if($value1['time']==$value2['time'] && $value1['location']==$value2['location'])
     {
         $value['count'] = $value1['count']+$value2['count'];
         $result[] = array("count"=>$value['count'],"time"=>$value1['time'],"location"=>$value1['location']);
     }
 }
}
var_dump($result);

working demo