0

我在下面写的代码有问题。基本上,当购物车中有 x 件商品时,它会回显文本“您在购物车中有 x 件商品”。但是,当没有商品时,它应该回显“您在购物车中没有任何商品”,而是什么也不回显。我究竟做错了什么?

<?php 
    $array = unserialize($_SESSION['__vm']['vmcart']); 
    foreach($array->products as $product){
        $amount = $product->amount;
        if ($amount != 0){ echo "You have $amount item(s) in the cart."; } 
        else { echo "You don't have any items in the cart."; } 
    }
?>
4

2 回答 2

0

这是因为代码没有出现在 for each 循环中。

<?php 
    $array = unserialize($_SESSION['__vm']['vmcart']); 
    if (count($array->products) > 0) {
      foreach($array->products as $product){
          $amount = $product->amount;
          echo "You have $amount item(s) in the cart."; 
          /* Do other thinks here. */
      }
    } else { 
     echo "You don't have any items in the cart."; 
    } 
?>

我不确定你为什么要使用循环顺便说一句。

于 2013-04-12T22:17:03.237 回答
0

删除你的 foreach 并使用它

if($size=sizeof($array->products))
echo "You have ".$size." item(s) in the cart.";
else
echo "You don't have any items in the cart.";
于 2013-04-12T22:18:04.867 回答