-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 出现不止一次,我想要一个 qty 的总和

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
        )

)
4

1 回答 1

2

像这样的东西应该工作

$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);
于 2012-06-22T17:23:00.257 回答