一、前言
在实际情况中,有时需要针对多维数组相同键值作相应的处理(四则运算、比较大小等)后才能够使用到实际情况中,现给出三维数组(多维数组可相应拓展)任意多个相同键值处理的函数,以备查阅。
二、代码
<?php
//任意多个相同键值的数组合并
//预先将所要合并的数组组装成一个新的数组 $arr = array(
'1' => array(
'1' => array(
"channelName" => "渠道1",
"firstRegisterTime" => "2018-12-20 10:23:57",
"firstChargeNum" => 168,
),
'2' => array(
"channelName" => "渠道2",
"firstRegisterTime" => "2018-12-20 10:23:57",
"firstChargeNum" => 127,
),
'3' => array(
"channelName" => "渠道3",
"firstRegisterTime" => "2018-12-10 11:23:57",
"firstChargeNum" => 69,
),
),
'2' => array(
'1' => array(
"channelName" => "渠道1",
"firstRegisterTime" => "2017-12-29 10:23:57",
"firstChargeNum" => 798,
),
'2' => array(
"channelName" => "渠道2",
"firstRegisterTime" => "2018-12-20 10:23:57",
"firstChargeNum" => 985,
),
'3' => array(
"channelName" => "渠道3",
"firstRegisterTime" => "2017-12-20 11:23:57",
"firstChargeNum" => 54,
),
),
);
print_r($arr);
$result = arr_format($arr);
print_r($result); /**
* [comm_sumarrs 多维数组相同键值处理合并]
* @param [array] $data [原始数据]
* @return [array] $res [合并完数据]
*
*/
function arr_format($arr){
$res = array();
// 三维数组,循环三次(foreach)
foreach ( $arr as $key => $value ) {
foreach( $value as $k=>$v ){
foreach ( $v as $k1 => $v1 ) { // 循环具体键值
if ( isset($res[$k][$k1]) ){
if ( $k1 == 'firstRegisterTime' ) { // 相同键值时间戳比较,更新为最早的
if( strtotime($v1) < strtotime($res[$k][$k1]) ){
$res[$k][$k1] = $v1;
}
}
if ( $k1 == 'firstChargeNum' ) { // 相同键值相加
$res[$k][$k1] += $v1;
}
}else{
$res[$k][$k1] = $v1;
}
}
}
}
return $res;
} ?>
三、运行结果
处理前数组:
Array
(
[1] => Array
(
[1] => Array
(
[channelName] => 渠道1
[firstRegisterTime] => 2018-12-20 10:23:57
[firstChargeNum] => 168
) [2] => Array
(
[channelName] => 渠道2
[firstRegisterTime] => 2018-12-20 10:23:57
[firstChargeNum] => 127
) [3] => Array
(
[channelName] => 渠道3
[firstRegisterTime] => 2018-12-10 11:23:57
[firstChargeNum] => 69
) ) [2] => Array
(
[1] => Array
(
[channelName] => 渠道1
[firstRegisterTime] => 2017-12-29 10:23:57
[firstChargeNum] => 798
) [2] => Array
(
[channelName] => 渠道2
[firstRegisterTime] => 2018-12-20 10:23:57
[firstChargeNum] => 985
) [3] => Array
(
[channelName] => 渠道3
[firstRegisterTime] => 2017-12-20 11:23:57
[firstChargeNum] => 54
) ) )
处理后数组:
Array
(
[1] => Array
(
[channelName] => 渠道1
[firstRegisterTime] => 2017-12-29 10:23:57
[firstChargeNum] => 966
) [2] => Array
(
[channelName] => 渠道2
[firstRegisterTime] => 2018-12-20 10:23:57
[firstChargeNum] => 1112
) [3] => Array
(
[channelName] => 渠道3
[firstRegisterTime] => 2017-12-20 11:23:57
[firstChargeNum] => 123
) )