2014-02-11 37 views
1

我正在返回大型數組(產品),並使用array_slice來只抓取前8個項目。array_slice加載其餘項目

我將實現一個「See More」按鈕,它將爲用戶加載前端的剩餘項目。

<?php 
    $split_output = array_slice($_associatedProducts, 0, 8);  // returns set number of products in array (8), for more button 
    ?> 

我的問題是,我如何然後返回數組中的其餘項,繼8顯示?這些項目將在用戶點擊「See More」時顯示。

在此先感謝!

+0

[下面是一個例子](http://ideone.com/lURVl8)使在查詢字符串的起始索引,並且使用的,作爲'array_slice'的開始位置。例如,您可以在鏈接的查詢字符串中提供'start'和'show':'mysite.php?start = 10&show = 10'。我建議用JSON發送整個數組,並允許JavaScript來管理演示文稿,如果這是一個選項,如@TimDev所建議的那樣。 – crush

回答

-1

使用該去拿剩餘的項目:

$more_output = array_slice($_associatedProducts, 8); 

然後將它們放在一個隱藏的DIV中:

<div class="moreProducts"> 
    Place your hidden Products here 
</div> 

風格:

.moreProducts { 
    display: none; 
} 

HTML鏈接:

<a href="javascript:;" class="showMore">More Products</a> 

的jQuery:

$('a.showMore').bind('click', function() { 
    $('.moreProducts').show(); 
}); 

上面的代碼只是一個例子。你必須改變它以滿足你的需求。

-1

您可以將剩下的部分與您離開的位置分開。第九項(偏移8)。如果您沒有提供array_slice的長度,它只會返回所有剩餘的物品。

$remaining_items = array_slice($_associatedProducts, 8); 

如果您不想在用戶單擊鏈接後執行此操作,則有多條路徑可以解決此問題。

  • 獲取數據異步與JS
  • 多頁,第一頁在查詢LIMIT 0,8中,看到更多的頁面沒有。
  • 只需將所有數據發送到該頁面,並將其餘產品初始隱藏並用按鈕顯示。
  • 還有更多...

下面的只要所有數據發送到頁面的例子,使剩餘產品最初是隱藏的,並用一個按鈕顯示它們。

這也可以用很多方式完成,這只是一個例子。

然後當點擊查看更多...你可以用javascript顯示剩餘的項目。

這種方式你甚至不需要切片。

實施例:

CSS:

.hide{ 
    display:none; 
} 

PHP/HTML

<ul id="productlist"> 
<?php 
$i=1; 
foreach($_associatedProducts as $product){ 
    $hide = ($i++>8)?' class="hide"':''; 
    echo "<li$hide>$product</li>"; 
} 
?> 
</ul> 
<button id="seemore">See more..</button> 

將生成:

<ul id="productlist"> 
    <li>product 1</li> 
    <li>product 2</li> 
    <li>product 3</li> 
    <li>product 4</li> 
    <li>product 5</li> 
    <li>product 6</li> 
    <li>product 7</li> 
    <li>product 8</li> 
    <li class="hide">product 9</li> 
    <li class="hide">product 10</li> 
</ul> 
<button>See more..</button> 

現在添加的jQuery:

$('#seemore').on('click', function(){ 
    $('#productlist>li.hide').removeClass('hide'); 
}); 
1

代替使用array_slice,將數組的所有值輸出到頁面,但將值從第九個值向前隱藏(可通過foreach循環和計數器變量輕鬆實現)。適用Javascript來上的按鈕的點擊取消隱藏這些值:

<?php 
$_associatedProducts = array(); // then add values to the array 
$num = 0; 
foreach($_associatedProducts as $prod){ 
    if(++$num <= 8){ 
    print("<div>$prod</div>"); 
    } 
    else{ 
    print("<div class=\"more\" style=\"display:none;\">$prod</div>"); 
    } 
} 
?> 
<button type="button" id="myButton">See More</button> 
<script type="text/javascript"> 
document.getElementById("myButton").onclick = function(){ 
var divs = document.getElementsByClassName("more"); 
var len = divs.length; 
    for(var i = 0; i < len; i++){ 
    divs[i].style.display = "block"; 
    } 
this.style.display = "none"; 
} 
</script> 
+0

這不是工作。你需要在我的回答中使用'count'。 –