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

时间:2015-01-29 00:02:59

标签: php arrays multidimensional-array

我发现这篇文章(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));

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

这就是我想输出的方式:

$array2

谢谢!

3 个答案:

答案 0 :(得分:0)

建立您所关联问题的已接受答案:

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

答案 1 :(得分:0)

执行此操作的简单方法( 没有嵌套循环 )将遍历$array1,检查$array2中是否存在相同的密钥1}}(假设它们已经按顺序排列)并在计算完成后创建一个新的数据数组。

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

答案 2 :(得分:0)

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