dongzhang1875 2017-11-23 15:02
浏览 32
已采纳

PHP关联数组过滤[关闭]

I have an associative array and I want to sum the duplicated values due to the duplicated elements in the key..

For better explain:

    array:6 [
  0 => array:4 [
    "itemsName" => "H&M Chemise#15 M.Colors Orange x Grey '17(red-l)"
    "itemsQuantity" => 3
    "itemsCode" => 101
    "itemsBarcode" => "101|60|78"
  ]

  1 => array:4 [
    "itemsName" => "H&M Chemise#15 M.Colors Orange x Grey '17(green-l)"
    "itemsQuantity" => 1
    "itemsCode" => 101
    "itemsBarcode" => "101|15|78"
  ]

  2 => array:4 [
    "itemsName" => "Polo Cap Multi Colors B-Logo(red-l)"
    "itemsQuantity" => 2
    "itemsCode" => 104
    "itemsBarcode" => "104|60|78"
  ]

  3 => array:4 [
    "itemsName" => "Polo Cap S-Logo White(green-l)"
    "itemsQuantity" => 1
    "itemsCode" => 107
    "itemsBarcode" => "107|15|78"
  ]

  4 => array:4 [
    "itemsName" => "H&M Chemise#15 M.Colors Orange x Grey '17(green-l)"
    "itemsQuantity" => 2
    "itemsCode" => 101
    "itemsBarcode" => "101|15|78"
  ]

  5 => array:4 [
    "itemsName" => "H&M Chemise#15 M.Colors Orange x Grey '17(red-l)"
    "itemsQuantity" => 3
    "itemsCode" => 101
    "itemsBarcode" => "101|60|78"
  ]
]

Problem:

You will find that the barcode 01|15|78 is duplicated in the array index 4 and 1 so I want to sum up the quantities in index 4 and 1 and make them a single array and it will be:

[ "itemsName" => "H&M Chemise#15 M.Colors Orange x Grey '17(green-l)" "itemsQuantity" => 3 "itemsCode" => 101 "itemsBarcode" => "101|15|78" ]

  • 写回答

1条回答 默认 最新

  • douqiao2471 2017-11-23 15:16
    关注

    Lets assume your array was saved under the variable $cart.

    You can use the PHP function array_reduce to walk through each item of your array, filter it and edit the values of other indices.

    $cart = array_reduce($cart, function($newCart, $item){
        $barCode = $item['itemsBarcode'];
        if (array_key_exists($barCode, $newCart)) {
            $newCart[$barCode]['itemsQuantity'] += $item['itemsQuantity'];
        } else {
            $newCart[$barCode] = $item;
        }
        return $newCart;
    }, []);
    

    If you need to have simple numeric array keys (to loop it through an for loop for example) use $cart = array_values($cart); afterwards.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决