【发布时间】:2011-02-07 14:09:16
【问题描述】:
我知道我这样做很糟糕......但我很难找到任何替代方案。我有一系列产品需要随机选择 4 个。 $rawUpsellList 是基于购物车中商品的所有可能追加销售的数组。每个值都是一个产品对象。我知道这是非常丑陋的代码,但我现在看不到替代方案......请有人让我摆脱痛苦,这样这段代码就无法投入生产......
$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;
}
}
发布此代码非常尴尬...
【问题讨论】: