PHP associative array filtering

Ahmed Essam

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

Philipp Maurer

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related