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.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料