count():参数必须是一个数组或在php中实现Countable错误的对象



我正在我的网站上创建一个添加到购物车的系统。

如果购物车中没有项目,则变量$cart设置为NULL

当我尝试回显购物车中的项目数时,会导致以下错误:count(): Parameter must be an array or an object that implements Countable

这是我的php代码:

<?php 
if ((isset($_SESSION['active_user_type']) && $_SESSION['active_user_type'] == "consumer") || !isset($_SESSION['active_user'])) {
?>
<div class="shopping_cart">
<div class="cart_title">
<a href="view_cart.php">Shopping cart</a>
</div>
<?php
$total = 0;
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
for ($i=0; $i<count($cart); $i++) {
$item_id = $cart[$i][0];
$query = "SELECT * FROM items WHERE id=$item_id";
$result = $db->query($query);
if ($row = $result->fetch()) {
$price = ($row['price']*$cart[$i][1]) + $row['shipping_price'];
}
$total += $price;
}
} else {
$cart = NULL;
}
?>
<div class="cart_details">
// the error seems to be from the line below:
<?php echo count($cart); ?><br />
<span class="border_cart"></span> Total: 
<span class="price">
<?php echo "BD " . number_format((float)$total,3,'.',''); ?>
</span>
</div>
<div class="cart_icon">
<a href="checkout.php" title="Checkout">
<img src="images/shoppingcart.png" alt="" width="48" height="48" border="0" />
</a>
</div>
</div>
<?php
}
?>

这是因为你指望的是"NULL",这样试试:

.
.
.
else
{
$cart = [];
}

这是因为你试图计算不可计数的东西(如何计算null中的元素数量?(。来自文件:

7.2.0:count((现在将对传递给array_or_countable参数的无效可计数类型发出警告。

因此在版本7.2.0之前不会发出此警告。在所有版本中,如果count(obj)中的obj不是有效的数组/可计数对象,则函数将返回1,但返回0count(null)除外。


您可以:

  1. 将其投射到数组
  2. 如果为空,则显式将其设置为空数组
  3. 在回显之前先进行检查

1:<?php echo count((array)$cart);?>

2:else { $cart = []; }

3:<?php ($cart == null) ? '' : echo count($cart);?>

$cart == NULL(在else子句中指定(时,由于NULL没有Countable接口,因此无法使用count。从PHP7.2开始,这将导致您看到的警告消息。

但当你没有购物车时,你似乎不应该试图输出购物车,所以你应该把代码移动到你的if块中,即

$total = 0;
if(isset($_SESSION['cart']))
{
$cart = $_SESSION['cart'];
for ($i=0; $i<count($cart); $i++)
{
$item_id = $cart[$i][0];
$query = "SELECT * FROM items WHERE id=$item_id";
$result = $db->query($query);
if ($row = $result->fetch())
{
$price = ($row['price']*$cart[$i][1]) + $row['shipping_price'];
}
$total += $price;
}
?>
<div class="cart_details"> <?php echo count($cart);?> <br />
<span class="border_cart"></span> Total: <span class="price"><?php echo "BD " . 
number_format((float)$total,3,'.',''); ?></span> </div>
<div class="cart_icon"><a href="checkout.php" title="Checkout"><img src="images/shoppingcart.png" 
alt="" width="48" height="48" border="0" /></a></div>
</div>
<?php
}
else
{
$cart = NULL;
}
?>

最新更新