標籤:
例如有如下數組:
$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);
PHP 二維數組合并(二)