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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化