如何从数组中排除数据?

时间:2012-08-22 02:33:51

标签: php

在产品页面上,我想要显示随机选择的其他4种产品,但从未显示已经显示的产品。显示的产品ID为$_product->getId(),所有产品都会进入$result[]数组,如下所示:

foreach($collection as $product){
    $result[]=$product->getId();
}

我正在使用$need = array_rand($result, 4);来获取4种随机产品的ID,但它可能包含展示产品的ID。如何从$_product->getId()数组中排除$need[]?谢谢。

4 个答案:

答案 0 :(得分:1)

请勿将您不希望展示的产品的ID放入$result

$currentProductId = $_product->getId();
foreach ($collection as $product) {
  if ($product->getId() != $currentProductId) $result[] = $product->getId();
}

答案 1 :(得分:0)

只是不将当前产品ID放在数组中是否可以接受?

foreach($collection as $product) {
    if( $product != $_product) $result[] = $product->getId();
}

答案 2 :(得分:0)

您可以先生成随机数,如下所示:

$rands = array();
while ($monkey == false){
    $banana = rand(0,4);
    if (in_array($banana, $rands) && $banana != $_product->getId()){ $rands[] = $banana; }

    if (sizeOf($rands) == 4){
        $monkey = true;
    }

}

然后你可以通过你的产品抓取器管道。显然,你需要自己弄清楚rand的界限,但你比我更了解你的应用程序。首先选择你的数字比计算记录要便宜得多,然后检查以确保它们是唯一的。

当然,如果这是由数据库支持的,您可以通过编写新查询来更优雅地解决它。

答案 3 :(得分:0)

如果您在结果中使用产品ID作为索引$result[],则可以在调用$result之前使用unset()array_rand()数组中删除当前产品像这样:

foreach($collection as $product){
    $result[$product->getId()] = $product->getId();
}
unset($result[$_product->getId()]);
$need = array_rand($result, 4);

此方法使您无需使用$need中的值来查找$result[]数组中的产品ID,因为$need中的值将是您的产品ID。< / p>

相关问题