I made a terrible loop .... help correct my logic, please

I know that I am doing it badly, but I do not see any alternatives. I have an array of products that I need to select 4 randomly. $ rawUpsellList is the collection of all possible upsells based on the elements in their cart. Each value is a product object. I know this is a terribly ugly code, but now I see no alternative ... someone, please pulled me out of my misery so that this code does not make it into production .....

$rawUpsellList = array(); foreach ($tru->global->cart->getItemList() as $item) { $product = $item->getProduct(); $rawUpsellList = array_merge($rawUpsellList, $product->getUpsellList()); } $upsellCount = count($rawUpsellList); $showItems = 4; if ($upsellCount < $showItems) { $showItems = $upsellCount; } $maxLoop = 20; $upsellList = array(); for ($x = 0; $x <= $showItems; $x++) { $key = rand(0, $upsellCount); if (!array_key_exists($key, $upsellList) && is_object($rawUpsellList[$key])) { $upsellList[$key] = $rawUpsellList[$key]; $x++; } if ($x == $maxLoop) { break; } } 

Posting this code was very confusing ...

+4
source share
3 answers

In fact, accidentally moving from an array is a tough nut to crack - even recently, Microsoft has had problems. This is a good code example for those whom I assume are not experts in algorithms, but can also be statistically distorted. As I said, this is hard to do right.

Luckily, PHP already has an array_rand function that seems to do what you want: return N elements randomly selected from the array. Is this what you are looking for?

 $upsellList = array_rand($rawUpsellList, 4); 
+6
source

I'm really not in PHP, but as an algorithm I will consider this pseudocode or something else:

 List<WhateverTypeYouWant> array; List<WhateverTypeYouWant> selectedElements; for (int i = 1; i <= 4; i++) { int randomIndex = random(array.size()); selectedElements.add(array[randomIndex]); array.remove(randomIndex); } 
+2
source

array_rand will allow you to select one or more elements at random from an array.

To use it (and save a lot of headache), just do something like

  $ upsellList = array_rand ($ rawUpsellList, 4);
+1
source

Source: https://habr.com/ru/post/1306838/


All Articles