PHP:根据键输入合并/组合数组中的值

时间:2012-06-22 17:14:39

标签: php arrays

嗯,我必须说,我感到失落的感觉操作应该足够快,以便寻找一个快速表现的组合。

我的数组看起来像

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
        )

)

1 个答案:

答案 0 :(得分:3)

这样的事情应该有效

$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'];
});

Here is a demo显示正确的输出。

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);