PHP数组中的常见值

时间:2015-10-09 07:18:02

标签: php arrays

我有两个数组

数组1:

$strong_areas=array(
                '192'=>57,
                '187'=>43,
                '121'=>85,
                '198'=>74
              );

数组2:

$weak_areas=array(
                '109'=>57,
                '187'=>54,
                '181'=>85,
                '198'=>25
            );

我需要像这样的结果数组:

array(
        '192'=>57, //57-0
        '187'=>-11, //43-54
        '121'=>85, //85-0
        '198'=>49, //74-25
        '109'=>-57, // 0-57
        '181'=>-85, //0-85
    )

到目前为止我尝试了什么:

//for common keys in both arrays
$temp=array_intersect_key($strong_areas,$weak_areas);

//for unique ones from first to second
$strong_final_array=array_diff_key($strong_areas, $weak_areas); 

//for unique ones from second to first 
$weak_final_array=array_diff_key($weak_areas, $strong_areas); 

foreach ($weak_final_array as &$value){
   $value *= (-1);
}

//returning final values for common keys in array  
$common=array();
foreach($temp as $key => $value){
    $common[$key]=$strong_areas[$key]-$weak_areas[$key];
} 

//getting final results
$final_array=array_merge($strong_final_array,$weak_final_array,$common);

问题是,上述程序是最佳做法还是有更简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

你可以这样使用

$final_result = array();
foreach (array_keys($strong_areas + $weak_areas) as $join_key) {
  $final_result[$join_key] = ( isset($strong_areas[$join_key]) ? $strong_areas[$join_key] : 0 ) - ( isset($weak_areas[$join_key]) ? $weak_areas[$join_key] : 0 );
}
print_r($final_result);

输出数组是

Array
(
[192] => 57
[187] => -11
[121] => 85
[198] => 49
[109] => -57
[181] => -85
)