Hello! There is an array foreach($products as $ val) {} :

 Array( [0] => Array ( [product_id] => 31 [quantity] => 5 [price] => $100.00 [total] => $500.00 ) [1] => Array ( [product_id] => 47 [quantity] => 2 [price] => $200.00 [total] => $400.00 ) [2] => Array ( [product_id] => 47 [quantity] => 2 [price] => $200.00 [total] => $400.00 ) [3] => Array ( [product_id] => 47 [quantity] => 2 [price] => $200.00 [total] => $400.00 ) [4] => Array ( [product_id] => 50 [quantity] => 1 [price] => $300.00 [total] => $300.00 ) [5] => Array ( [product_id] => 50 [quantity] => 1 [price] => $300.00 [total] => $300.00 ) [6] => Array ( [product_id] => 50 [quantity] => 1 [price] => $300.00 [total] => $300.00 ) 

)

How to calculate the amount of quantuty , if the product_id same, after unset remove the duplicate product_id

The result should be:

 Array( [0] => Array ( [product_id] => 31 [quantity] => 5 [price] => $100.00 [total] => $500.00 ) [1] => Array ( [product_id] => 47 [quantity] => 6 [price] => $200.00 [total] => $1200.00 ) [2] => Array ( [product_id] => 50 [quantity] => 3 [price] => $300.00 [total] => $900.00 ) 
  • added to the question: foreach ($ products as $ val) {...} - ultimatum
  • From the box opancart2.2 - ee you can not touch it, you need to rebuild it in the controller - ultimatum
  • 2
    I've been thinking. And let's close this offtopic "well, write me a code in a quick way"? - Ipatiev
  • I also write ...... you do not want to help, do not help, we somehow somehow remembered on one question .... - ultimatum
  • one
    @ Ipatiev Dear, on principle, the question-answer is based on the policy of the site, and instead of spamming you, it would be better for you to write the answer yourself, if of course there is enough cleat. Be mutually polite to the Lord!) - hold me seven

3 answers 3

 $new_arr=array(); foreach ($products as $key => $value) { $product_id=$value['product_id']; $quantity=$value['quantity']; $price=$value['price']; if (array_key_exists($product_id, $new_arr)) { $new_quantity=$new_arr[$product_id]['quantity']+$quantity; $new_arr[$product_id]['quantity']=$new_quantity; $new_arr[$product_id]['total']=$new_quantity*$price; } else { $new_arr[$product_id]['quantity']=$quantity; $new_arr[$product_id]['price']=$price; $new_arr[$product_id]['total']=$quantity*$price; } } 

Initially, it would be necessary to do the array keys not with an order in sequence, but with a unique product ID. It would take a lot of trouble. And the currency should be stored separately ($ 200 * 2 does not count).

Added based on comments

  $products=Array( '0' => Array ( 'product_id' => '47', 'quantity' => '5', 'price' => '200.00', 'total' => '1000.00', 'thumb' => 'thumb.00', 'name' => 'name.00', 'model' => 'model.00', 'size' => '34' ), '1' => Array ( 'product_id' => '47', 'quantity' => '2', 'price' => '200.00', 'total' => '400.00', 'thumb' => 'thumb.00', 'name' => 'name.00', 'model' => 'model.00', 'size' => '56' ) ); $new_arr=array(); $balast_values_names=array(1 => 'thumb', 2 => 'name', 3 => 'model'); // тут все статичные переменные foreach ($products as $key => $value) { $product_id=$value['product_id']; $quantity=$value['quantity']; $price=$value['price']; /* Играем на свойстве ключей массивов - может быть только один уникальный ключ. И в качестве ключа берём product_id. Перебираем циклом (немного выше мы уже начали перебор) все значения исходного массива. И формируем новый. Ключами нового массива будет product_id исходного. Таким образом, если встретим в исходном массиве два товара с одним product_id, то более новый перезапишет более старый в новом массиве. А нам нужно сохранить все данные. Особеннно количество товаров. Потому array_key_exists($product_id, $new_arr) проверяет, есть ли у нас в новом массиве уже значение ключа равное product_id из исходого массива Если есть, до дополняем в новом массиве его дополнительными данными из старого (добавляем количество заказов, пересчитываем стоимость и т.п.) Если нет, то просто добавляем все данные */ if (array_key_exists($product_id, $new_arr)) { $new_quantity=$new_arr[$product_id]['quantity']+$quantity; $new_arr[$product_id]['quantity']=$new_quantity; $new_arr[$product_id]['total']=$new_quantity*$price; //это код для размеров обуви (если от размера не зависит цена) $want_to_add_in_array_size=$value['size']; //тут смотрим, если размер обуви, который хотим добавить не совпадает с теми, что уже есть в новом массиве, то добавляем его. А если совпадает, то ничего не делаем if (!in_array($want_to_add_in_array_size, $new_arr[$product_id]['size'])) { $new_arr[$product_id]['size'][]=$want_to_add_in_array_size; } } else { $new_arr[$product_id]['quantity']=$quantity; $new_arr[$product_id]['price']=$price; $new_arr[$product_id]['total']=$quantity*$price; //если каждый ИД товара - уникальная единица, то (размеры предусмотрены ниже) //переносим все значения статичным переменных foreach ($balast_values_names as $key2 => $balast) { $new_arr[$product_id][$balast]=$value[$balast]; } //размеры загоняем сюда (если от размера не зависит стоимость, конечно) $new_arr[$product_id]['size'][]=$value['size']; } } print_r($products); echo '<br><br><br>'; print_r($new_arr); 

As a result, we get

 Array ( [47] => Array ( [quantity] => 7 [price] => 200.00 [total] => 1400 [thumb] => thumb.00 [name] => name.00 [model] => model.00 [size] => Array ( [0] => 34 [1] => 56 ) ) ) 
  • I work with currency - do not bother with it. generally works, is there an option to make an auto-add, all values ​​except for which we change, I just have 20 pieces) - ultimatum
  • Are they static? Those. we have here all three variables (quantity, price, total) are not static - they are used for calculations or are calculated. And other variables? What are they for? Give an example of at least one product with all the variables. For example, everything for [product_id] => 31 - n.osennij
  • Yes, they are used for calculations, this info goes to the basket. It reads poorly, here is 31 [0] => Array ([product_id] => 31 [cart_id] => 119 [thumb] => shoes.loc / image / cache / catalog / 1234-100x100.jpg [name] => Name 9 [model] => Product 4 [recurring] => [quantity] => 5 [price] => $ 100.00 [total] => $ 500.00 [href] => site.loc / index.php? Route = product / product & product_id = 31 ) - ultimatum
  • this product doesn’t take duplicates and draws correctly by default, I’m on my way too)) $ total is left to draw - ultimatum
  • @ultimatum But what is the reason that the same product may appear several times in the source array? Is this a situation when a person ordered one shoe and then added it to the basket somewhere else? Then why not immediately make a normal array? Initially? Okay. The question is different. Product ID - is it really a unique ID? Ie, for example, we have boots with ID 32 but in different colors. And each color is different? Or is this situation excluded? - n.osennij

If you need a unique result, maybe so?

 <?php $uniqid = array(); $uniqArray = array(); $count = 0; foreach($products as $val) { if(!in_array($val['product_id'],$uniqid)){ array_push($uniqArray,$val); $count++; } } print_r($uniqArray); print_r($count); ?> 
  • gives an empty array ...., ideally, it is possible to total, but this is not necessary - ultimatum
  • @ultimatum You can simply insert the counter into the loop and get the number of the array ... that the result is empty, check the incoming array, is there exactly the structure you showed? - Arsen
  • In general, it’s probably not isset , a in_array and not $count++ , a $count+= $val['quantity']; - users
  • oops, litter, automatically inserted)) right now, correct - Arsen
  • ultimatum you need the number of entries in the array or the number of products? as rightly noted by @users, but it seemed to me that you need to get the amount of the array ..)) - Arsen

Something like this:

 function getArray($products) { $products_new = []; foreach($products as $key => $val) { if(!isset($products_new[$val['product_id']])) { $products_new[$val['product_id']]["quantity"] = $val['quantity']; $products_new[$val['product_id']]["price"] = $val['price']; } else { $products_new[$val['product_id']]["quantity"] += $val['quantity']; } $products_new[$val['product_id']]["total"] = $val['total'] * $products_new[$val['product_id']]["quantity"]; } return $products_new; } print_r(getArray($products)); 

Well, ghosts to the old mind (if necessary):

 function getOldArray($products_new){ $products = []; foreach($products_new as $key => $val) { $products[] = [ "product_id" => $key, "quantity" => $val['quantity'], "price" => $val['price'], "total" => $val['total'], ]; } return $products; } print_r(getOldArray(getArray($products))); 
  • Close but not quite ... Array ([0] => 31 [1] => 47 [2] => 50) - ultimatum
  • @ultimatum I understand how you need the amount of quantuty for a certain product_id ? - users
  • Yes! I added the expected result in response. Thank you) - ultimatum