douji5329 2019-03-07 08:26
浏览 40
已采纳

如何在数组中查找double值并组合double值

I'm working on a way to filter out double values, as my example below shows that the are products present in the array that are basically double and should be combined(make a new key with the values combined).

The product should be combined by api_id.

//old current array
[products] => Array
    (
        [product_5c7fb5f72f9d5_192] => Array
            (
                [record_id] => 84721
                [api_id] => 192
                [amount] => 12
                [cost_price] => 3.36
            )
        [product_5c7fb5f72fe49_192] => Array
            (
                [record_id] => 84722
                [api_id] => 177
                [amount] => 1
                [cost_price] => 1.09
            )
        [product_5c7fb5f7301b2_192] => Array
            (
                [record_id] => 84724
                [api_id] => 192
                [amount] => 24
                [cost_price] => 6.72
            )
        [product_5c7fb5f7301b2_192] => Array
            (
                [record_id] => 84725
                [api_id] => 192
                [amount] => 24
                [cost_price] => 6.72
            )
    )

// this should be new new array
[products] => Array
    (
        [product_5c7fb5f72f9d5_192] => Array
            (
                [record_id] => 84721
                [api_id] => 192
                [amount] => 60//new value
                [cost_price] => 16.8//new value
            )
        [product_5c7fb5f72fe49_192] => Array
            (
                [record_id] => 84722
                [api_id] => 177
                [amount] => 1
                [cost_price] => 1.09
            )

    )
  • 写回答

1条回答 默认 最新

  • doushi8186 2019-03-07 08:30
    关注

    You can use array_reduce:

    $products = array_reduce($products, function ($carry, $product) {
        if (!isset($carry[$product['api_id']])) {
            $carry[$product['api_id']] = $product;
        }
        else {
            $carry[$product['api_id']]['amount'] += $product['amount'];
            $carry[$product['api_id']]['cost_price'] += $product['cost_price'];
        }
    
        return $carry;
    }, []);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误