2012-08-22 36 views
0

在產品頁面上,我想顯示其他4種隨機選擇的產品,但從未顯示已經顯示的產品。所顯示的一個的產品ID爲$_product->getId(),所有的產品進​​入一個$result[]數組是這樣的:如何從數組中排除數據?

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

我使用$need = array_rand($result, 4);拿到4種隨機產品的ID,但它可能包含的ID展出的產品。如何從$need[]陣列中排除$_product->getId()?謝謝。

回答

1

不要將產品的ID,你不希望顯示爲$result

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

只是不把當前的產品ID放在數組中嗎?

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

這應該是一個評論,Konlink。 –

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的範圍,但是你比我更瞭解你的應用。首先挑選你的數字比拉動記錄計算便宜得多,然後檢查確保它們是唯一的。

當然,如果這是數據庫支持的,你可以通過編寫一個新的查詢來更加優雅地解決它。

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。

相關問題