我有一个使用多维数组的工作脚本,并将数据库中的项目引入用户购物车,但列表不断增长。我只想在购物车中显示2个商品,如果购物车中的商品数> 2,则加载接下来的两个商品。
以下是引入购物车项目的工作代码。
$cartoutput = "";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<font>Your Cart is currently empty.</font>";
}
else{
$i=0;
foreach($_SESSION["cart_array"] as $each_item){
$i++;
$cartoutput .="<h2>Cart Item $i</h2>";
while(list($key, $value) = each($each_item)){
$cartoutput .="$key: $value <br /><br />";
}
}
}
这是我做过的事:哪些不能正常工作:
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) > 2){
$start = (isset($_GET['start']) ? (int)$_GET['start'] : 0); //setting the get function for pagnation
echo "<table width=\"1024\" align=\"center\" >";
echo "<tr height=\"50\"></tr>";
echo "<tr>";
$count = $_SESSION["cart_array"];
$prev = $start - 2;
if ($prev >= 0) {
echo '<td><a href="?start=' . $prev . '">Previous Items</a></td>';
}
$next = $start + 2;
if ($next < $count) {
echo '<td><a href="?start=' . $next . '">Next Items</a></td>';
}
echo "</tr>";
echo "</table>";
}
任何人都可以告诉我如何将用户项目限制为每页2个,如果超过2个,则添加下一个和上一个按钮吗?
谢谢
答案 0 :(得分:1)
我认为你这里有一个小问题。而不是 $ count = $ _SESSION [“cart_array”];
我认为你的意思是: $ count = count($ _ SESSION [“cart_array”]);
答案 1 :(得分:0)
<?php
session_start();
$_SESSION['cart_array_start'] = $_GET['start'] ;
$_SESSION['cart_array'] = array("a", "b", "c", "d", "e", "f", "g", "h", "i");
$cartoutput = "";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<font>Your Cart is currently empty.</font>";
}
else{
$i=0;
//set our start session to 1 if it doesn't exist.
if (!isset($_SESSION['cart_array_start'])){
$_SESSION['cart_array_start'] = 1 ;
}
$first_product = $_SESSION['cart_array_start'] ;
//echo $first_product ;
$last_product = $_SESSION['cart_array_start'] + 1 ;
foreach($_SESSION["cart_array"] as $each_item){
$i++;
//echo $i ;
if ($i == $first_product || $i == $last_product){
$cartoutput .="<h2>Cart Item $i</h2>";
$key = $i - 1 ;
$cartoutput .="$key: $each_item <br /><br />";
}
}
}
echo $cartoutput ;
//code to start at the previous page.
if (empty($_SESSION['cart_array_start']) || $_SESSION['cart_array_start'] <= 2) {
//they dont get a back button because they are on the first page.
}else{
$back = $_SESSION['cart_array_start'] - 2 ;
echo "<a href=\"test.php?start=" . $back . "\">Back one page</a><br />";
}
//next page code.
if (count($_SESSION['cart_array']) > 2){
//start to display it - but lets check to see if they are on the last page first.
$next = $_SESSION['cart_array_start'] + 2 ;
//give our product in cart count plus one because we want to display the last page even if it only has 1 product.
$products = count($_SESSION['cart_array']) + 1 ;
if ($next > $products){
//do nothing because nothing will be on that page.
}else{
//give them a next button.
echo "<a href=\"test.php?start=" . $next . "\">next page</a>";
}
}
?>