PHP关联数组过滤

时间:2017-11-23 15:02:14

标签: php arrays algorithm loops

我有一个关联数组,我想根据密钥中的重复元素对重复值求和。

  

为了更好地解释:

    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"
  ]
]
  

问题:

您会发现条形码 01 | 15 | 78 在数组索引 4和1 中重复,因此我想总结索引中的数量4和1 并使它们成为一个数组,它将是:

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

1 个答案:

答案 0 :(得分:2)

让我们假设您的数组已保存在变量$cart下。

您可以使用PHP函数array_reduce遍历数组中的每个项目,过滤它并编辑其他索引的值。

$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;
}, []);

如果您需要使用简单的数字数组键(例如,通过for循环将其循环),请在之后使用$cart = array_values($cart);