PHP 二维数组合并(二)
例如有如下数组:
$arr = array( 0=>array( ‘product‘=>‘120‘, ‘type‘=>0 ), 1=>array( ‘product‘=>‘120‘, ‘type‘=>0 ), 2=>array( ‘product‘=>‘120‘, ‘type‘=>1 ), 3=>array( ‘product‘=>‘121‘, ‘type‘=>0 ), 4=>array( ‘product‘=>‘121‘, ‘type‘=>1 ), 5=>array( ‘product‘=>‘122‘, ‘type‘=>2 ), 6=>array( ‘product‘=>‘122‘, ‘type‘=>3 ), 7=>array( ‘product‘=>‘122‘, ‘type‘=>3 ), 8=>array( ‘product‘=>‘122‘, ‘type‘=>3 ), 9=>array( ‘product‘=>‘123‘, ‘type‘=>2 ), );
要求:
① 相同 product 值的数组要合并成一个数组,并计算具有相同 product 的数组的个数;
② 计算相同 product 值的数组的 type,相同的 type 保留一个,并计该 type 相加的数量;不同的 type 也进行保留,数量为1
即将上面的数组转换为下面的数组:
array 2 => array ‘product‘ => string ‘120‘ (length=3) ‘count‘ => int 3 ‘newtype‘ => array 0 => int 2 1 => int 1 4 => array ‘product‘ => string ‘121‘ (length=3) ‘count‘ => int 2 ‘newtype‘ => array 0 => int 1 1 => int 1 8 => array ‘product‘ => string ‘122‘ (length=3) ‘count‘ => int 4 ‘newtype‘ => array 2 => int 1 3 => int 3 9 => array ‘product‘ => string ‘123‘ (length=3) ‘count‘ => int 1 ‘newtype‘ => array 2 => int 1
php:
<?php $arr = array( 0=>array( ‘product‘=>‘120‘, ‘type‘=>0 ), 1=>array( ‘product‘=>‘120‘, ‘type‘=>0 ), 2=>array( ‘product‘=>‘120‘, ‘type‘=>1 ), 3=>array( ‘product‘=>‘121‘, ‘type‘=>0 ), 4=>array( ‘product‘=>‘121‘, ‘type‘=>1 ), 5=>array( ‘product‘=>‘122‘, ‘type‘=>2 ), 6=>array( ‘product‘=>‘122‘, ‘type‘=>3 ), 7=>array( ‘product‘=>‘122‘, ‘type‘=>3 ), 8=>array( ‘product‘=>‘122‘, ‘type‘=>3 ), 9=>array( ‘product‘=>‘123‘, ‘type‘=>2 ), ); var_dump($arr); //首先对数组排序,例如:order by product asc,type asc $i = 1; $j = 1; $newtype = array(); foreach($arr as $k=>$v){ if($k < count($arr)-1){ if($arr[$k][‘product‘] == $arr[$k+1][‘product‘]){ if($arr[$k][‘type‘] == $arr[$k+1][‘type‘]){ $j++; $newtype[$arr[$k][‘product‘]][$arr[$k+1][‘type‘]] = $j; }else{ $j = 1; $newtype[$arr[$k][‘product‘]][$arr[$k+1][‘type‘]] = $j; } $i++; $arr[$k+1][‘count‘] = $i; $arr[$k][‘del‘] = 1; }else{ $j = 1; $newtype[$arr[$k+1][‘product‘]][$arr[$k+1][‘type‘]] = $j; $i = 1; $arr[$k+1][‘count‘] = $i; } } } foreach ($arr as $k=>$v) { if(@$arr[$k][‘del‘]){ unset($arr[$k]); } } echo ‘<hr>‘; var_dump($arr); echo ‘<hr>‘; var_dump($newtype); foreach($arr as $key=>$val){ foreach ($newtype as $k => $v) { if($arr[$key][‘product‘] == $k){ $arr[$key][‘newtype‘] = $v; } } unset($arr[$key][‘type‘]); } echo ‘<hr>‘; var_dump($arr);
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。