Web*_*net 4 php arrays random loops
我知道我这样做的方式很糟糕......但我很难看到任何其他选择.我有一系列产品需要随机选择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;
}
}
Run Code Online (Sandbox Code Playgroud)
发布此代码非常令人尴尬......
实际上,从阵列中随机抽取是一个难以破解的难题 - 即使微软最近遇到了麻烦.对于我认为不是算法专家的人来说,这是一个不错的代码示例,但也可能在统计上存在偏差.正如我所说,很难做到这一点.
值得庆幸的是,PHP已经有了函数array_rand,它似乎可以做你想要的:返回从数组中随机选择的N个项.这就是你要找的东西吗?
$upsellList = array_rand($rawUpsellList, 4);
Run Code Online (Sandbox Code Playgroud)