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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。