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 ...
source share