php 俩个二维数组合并,根据相同的值,去合并数组

2024年12月02日 18:03
有2个网友回答
网友(1):

不知道你有没有想过,数组不要使用0、1、2、....这些下标,而是使用主键作为下标,例如:

$test = array (
    '20181005' => array('openup'=>1,'shenhe'=>5,'rejection'=>0,'adopt'=>1),
    '20181006' => array('openup'=>1,'shenhe'=>5,'rejection'=>0,'adopt'=>1),
    '20181007' => array('openup'=>1,'shenhe'=>5,'rejection'=>0,'adopt'=>1)
);

这样是不是怎么合并都简单了呢

网友(2):

$test = array( '0' => array( 'days' => 20181005, 'openup' => 1, 'shenhe' => 0, 'rejection' => 0, 'adopt' => 0 ), '1' => array( 'days' => 20181006, 'openup' => 3, 'shenhe' => 0, 'rejection' => 0, 'adopt' => 0 ), '2' => array( 'days' => 20181007, 'openup' => 1, 'shenhe' => 0, 'rejection' => 0, 'adopt' => 0 ), '3' => array( 'days' => 20181008, 'openup' => 1, 'shenhe' => 0, 'rejection' => 0, 'adopt' => 0 ), '4' => array( 'days' => 20181009, 'openup' => 5, 'shenhe' => 0, 'rejection' => 0, 'adopt' => 0 ));
$data = array( '0' => array( 'days' => 20181006, 'shenhe' => 5, 'rejection' => 0, 'adopt' => 3 ), '1' => array( 'days' => 20181008, 'shenhe' => 4, 'rejection' => 2, 'adopt' => 1));

$arrTest = array_merge($test,$data);
$result = array();
foreach($arrTest as $val){
$key = $val['days'];
if(!isset($result[$key])){
$result[$key] = $val;
}else{
$result[$key]['shenhe'] += $val['shenhe'];
$result[$key]['rejection'] += $val['rejection'];
$result[$key]['adopt'] += $val['adopt'];
}
}
print_r(array_values($result));