php从数组中删除重复的子数组并计算它们

时间:2017-03-31 01:13:57

标签: php arrays

我有包含4个字段的数组数组,我想删除所有具有相同前3个值的子数组并将它们的第4个值相加。请帮忙。

$a = [
       ["123", "XL", "blue", 1],
       ["345", "L", "black", 1],
       ["534", "S", "white", 2],
       ["345", "L", "black", 4]
     ]
$a = fixArray($a);

$a = [
       ["123", "XL", "blue", 1],
       ["345", "L", "black", 5],
       ["534", "S", "white", 2]
     ]

2 个答案:

答案 0 :(得分:0)

试试这个:

function FixArray($arr)
{
    // create a copy to work with
    $ca = $arr; 

    // we're gonna fill this one and return it
    $cr = array();

    for($i=0; $i<count($arr); $i++){

        $tmp = $arr[$i];

        for($j=0; $j<count($arr); $j++){

            // empty the same element in the copy so we don't double count it.
            if($i == $j){
                $ca[$j][0] = "";
                $ca[$j][1] = "";
                $ca[$j][2] = "";
                $ca[$j][3] = "";
            }

            if($tmp[0] == $ca[$j][0] && $tmp[1] == $ca[$j][1] && $tmp[2] == $ca[$j][2]){
                // if matched, add then push into the return array then empty the element from the copy
                array_push($cr, [$ca[$j][0], $ca[$j][1], $ca[$j][2], ($ca[$j][3] + $tmp[3])]);
                $ca[$j][0] = "";
                $ca[$j][1] = "";
                $ca[$j][2] = "";
                $ca[$j][3] = "";                    
            }           
        }   
    }

    return $cr;
}

答案 1 :(得分:0)

有关方法的解释,请参阅内联注释。

代码:(Demo

$a=[
   ["123", "XL", "blue", 1],
   ["345", "L", "black", 1],
   ["534", "S", "white", 2],
   ["345", "L", "black", 4]
];

function merge_sum($array){
    foreach($array as $a){
        $tmp_key=implode('_',array_slice($a,0,3));  // generate temporary key from first three elements in row
        if(!isset($result[$tmp_key])){
            $result[$tmp_key]=$a;  // instantiate the unique row
        }else{
            $result[$tmp_key][3]+=$a[3];  // sum the new quantity and the old quantity
        }
    }
    return array_values($result);  // reindex the rows (remove the temporary keys)
}

var_export(merge_sum($a));

输出:

array (
  0 => 
  array (
    0 => '123',
    1 => 'XL',
    2 => 'blue',
    3 => 1,
  ),
  1 => 
  array (
    0 => '345',
    1 => 'L',
    2 => 'black',
    3 => 5,
  ),
  2 => 
  array (
    0 => '534',
    1 => 'S',
    2 => 'white',
    3 => 2,
  ),
)