I made a horrible loop.... help fix my logic please
- by Webnet
I know I'm doing this a bad way... but I'm having trouble seeing any alternatives. I have an array of products that I need to select 4 of randomly. $rawUpsellList is an array of all of the possible upsells based off of the items in their cart. Each value is a product object. I know this is horribly ugly code but I don't see an alternative now.... someone please put me out of my misery so this code doesn't make it to 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 highly embarassing...