【问题标题】:I made a horrible loop.... help fix my logic please我做了一个可怕的循环......请帮助解决我的逻辑
【发布时间】: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;
    }
}

发布此代码非常尴尬...

【问题讨论】:

    标签: php arrays random loops


    【解决方案1】:

    实际上,从数组中随机抽取是一个难以破解的难题 - even Microsoft had trouble recently。对于我认为不是算法专家但也可能在统计上存在偏差的人来说,这是一个不错的代码示例。正如我所说,要做到这一点很难。

    谢天谢地,PHP 已经有了函数array_rand,它似乎可以满足您的要求:返回从数组中随机选择的 N 个项目。这就是你要找的东西吗?

    $upsellList = array_rand($rawUpsellList, 4);
    

    【讨论】:

      【解决方案2】:

      我不是很喜欢 PHP,但作为一种算法,我会考虑这个伪代码或其他什么:

      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);
      }
      

      【讨论】:

      • 这是Fisher-Yates shuffle的基本实现:)
      • 哈,谢谢:)虽然我用过很多次,但我不知道它有名字。
      • ...我也刚刚注意到 Markdown 以某种方式破坏了 URL。 en.wikipedia.org/wiki/Fisher-Yates_shuffle
      • 这不起作用,因为它只会在 4 个循环后停止,我需要它在 4 个循环后不停止,但直到选择了 4 个随机产品才停止。
      • 但是在循环的每次迭代中都会选择一个新元素。什么意思?
      【解决方案3】:

      array_rand 可以让您从数组中随机选择一个或多个元素。

      要使用它(并为自己省去很多麻烦),只需执行类似的操作

      $upsellList = array_rand($rawUpsellList, 4);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-03
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        相关资源
        最近更新 更多