PHP:根据键条目合并/组合数组上的值

PHP:根据键条目合并/组合数组上的值,php,arrays,Php,Arrays,嗯,我必须说,我有一种感觉,操作应该足够快,所以寻找一个快速执行联合收割机迷失 我的数组看起来像 Array ( [0] => Array ( [id] => 35 [item] => Ball Pen [qty] => 1 [price] => 23 [total] => 23 ) [1]

嗯,我必须说,我有一种感觉,操作应该足够快,所以寻找一个快速执行联合收割机迷失

我的数组看起来像

Array
(
    [0] => Array
        (
            [id] => 35
            [item] => Ball Pen
            [qty] => 1
            [price] => 23
            [total] => 23
        )

    [1] => Array
        (
            [id] => 34
            [item] => Summer vest
            [qty] => 1
            [price] => 23
            [total] => 23
        )

    [2] => Array
        (
            [id] => 34
            [item] => Summer vest
            [qty] => 3
            [price] => 23
            [total] => 69
        )
)
作为输出,如果id不止一次出现,我需要一个数量的总和

Array
(
    [35] => Array
        (
            [id] => 35
            [item] => Ball Pen
            [qty] => 1
            [price] => 23
            [total] => 23
        )

    [34] => Array
        (
            [id] => 34
            [item] => Summer vest
            [qty] => 4
            [price] => 46
            [total] => 92
        )

)

像这样的东西应该有用

$sum = array();
$input = array(); // Your array
array_walk( $input, function( $el) use( &$sum) {
    if( !isset( $sum[ $el['id'] ] ))
        $sum[ $el['id'] ] = 0;
    $sum[ $el['id'] ] += $el['qty'];
});
显示正确的输出

array(2) { [35]=> int(1) [34]=> int(4) } 
您可以通过以下方式获得更新的输出:

$output = array();
$input = array(); // Your array
array_walk( $input, function( $el) use( &$output) {
    if( !isset( $output[ $el['id'] ] ))
        $output[ $el['id'] ] = array( 
            'id' => $el['id'], 
            'item' => $el['item'], 
            'qty' => 0, 
            'price' => 0, 
            'total' => 0
        );

    $output[ $el['id'] ]['qty'] += $el['qty'];
    $output[ $el['id'] ]['price'] += $el['price'];
    $output[ $el['id'] ]['total'] += $el['total'];
});
var_dump( $output);