1、前言php
在實際狀況中,有時須要針對多維數組相同鍵值做相應的處理(四則運算、比較大小等)後纔可以使用到實際狀況中,現給出三維數組(多維數組可相應拓展)任意多個相同鍵值處理的函數,以備查閱。數組
2、代碼函數
1 <?php 2 //任意多個相同鍵值的數組合並 3 //預先將所要合併的數組組裝成一個新的數組 4 5 $arr = array( 6 '1' => array( 7 '1' => array( 8 "channelName" => "渠道1", 9 "firstRegisterTime" => "2018-12-20 10:23:57", 10 "firstChargeNum" => 168, 11 ), 12 '2' => array( 13 "channelName" => "渠道2", 14 "firstRegisterTime" => "2018-12-20 10:23:57", 15 "firstChargeNum" => 127, 16 ), 17 '3' => array( 18 "channelName" => "渠道3", 19 "firstRegisterTime" => "2018-12-10 11:23:57", 20 "firstChargeNum" => 69, 21 ), 22 ), 23 '2' => array( 24 '1' => array( 25 "channelName" => "渠道1", 26 "firstRegisterTime" => "2017-12-29 10:23:57", 27 "firstChargeNum" => 798, 28 ), 29 '2' => array( 30 "channelName" => "渠道2", 31 "firstRegisterTime" => "2018-12-20 10:23:57", 32 "firstChargeNum" => 985, 33 ), 34 '3' => array( 35 "channelName" => "渠道3", 36 "firstRegisterTime" => "2017-12-20 11:23:57", 37 "firstChargeNum" => 54, 38 ), 39 ), 40 ); 41 print_r($arr); 42 $result = arr_format($arr); 43 print_r($result); 44 45 /** 46 * [comm_sumarrs 多維數組相同鍵值處理合並] 47 * @param [array] $data [原始數據] 48 * @return [array] $res [合併完數據] 49 * 50 */ 51 function arr_format($arr){ 52 $res = array(); 53 // 三維數組,循環三次(foreach) 54 foreach ( $arr as $key => $value ) { 55 foreach( $value as $k=>$v ){ 56 foreach ( $v as $k1 => $v1 ) { // 循環具體鍵值 57 if ( isset($res[$k][$k1]) ){ 58 if ( $k1 == 'firstRegisterTime' ) { // 相同鍵值時間戳比較,更新爲最先的 59 if( strtotime($v1) < strtotime($res[$k][$k1]) ){ 60 $res[$k][$k1] = $v1; 61 } 62 } 63 if ( $k1 == 'firstChargeNum' ) { // 相同鍵值相加 64 $res[$k][$k1] += $v1; 65 } 66 }else{ 67 $res[$k][$k1] = $v1; 68 } 69 } 70 } 71 } 72 return $res; 73 } 74 75 ?>
3、運行結果spa
處理前數組:code
1 Array 2 ( 3 [1] => Array 4 ( 5 [1] => Array 6 ( 7 [channelName] => 渠道1 8 [firstRegisterTime] => 2018-12-20 10:23:57 9 [firstChargeNum] => 168 10 ) 11 12 [2] => Array 13 ( 14 [channelName] => 渠道2 15 [firstRegisterTime] => 2018-12-20 10:23:57 16 [firstChargeNum] => 127 17 ) 18 19 [3] => Array 20 ( 21 [channelName] => 渠道3 22 [firstRegisterTime] => 2018-12-10 11:23:57 23 [firstChargeNum] => 69 24 ) 25 26 ) 27 28 [2] => Array 29 ( 30 [1] => Array 31 ( 32 [channelName] => 渠道1 33 [firstRegisterTime] => 2017-12-29 10:23:57 34 [firstChargeNum] => 798 35 ) 36 37 [2] => Array 38 ( 39 [channelName] => 渠道2 40 [firstRegisterTime] => 2018-12-20 10:23:57 41 [firstChargeNum] => 985 42 ) 43 44 [3] => Array 45 ( 46 [channelName] => 渠道3 47 [firstRegisterTime] => 2017-12-20 11:23:57 48 [firstChargeNum] => 54 49 ) 50 51 ) 52 53 )
處理後數組:orm
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 ) )