二维数组过滤相同元素 并计算和值函数

<?php
$array = array (
        Array ("goods_id" => "001", "goods_num" => 5 ), 
        Array ("goods_id" => "002", "goods_num" => 10 ), 
        Array ("goods_id" => "003", "goods_num" => 3 ), 
        Array ("goods_id" => "002", "goods_num" => 4 ) 
        );

/**
 * 二维数组过滤相同元素 并计算和值
 * 2011-07-18
 */
function array_2d_count_key($_2dArray, $key, $key2) {
    $nArray = array ();
    foreach ( $_2dArray as $k ) {
        $ckey = $k [$key];
        $cVal = $k [$key2];
        $cArray = array ($ckey => $cVal );
        if (array_key_exists ( $ckey, $nArray )) {
            $nArray [$ckey] = $cVal + $nArray [$ckey];
        } else {
            $nArray [$ckey] = $cVal;
        }
    }
    return $nArray;
}

print_r ( array_2d_count_key ( $array, 'goods_id', 'goods_num' ) );
?>

Leave a Reply

(will not be published)