PHP多维数组+ array_key_exists无法正常工作

时间:2016-08-16 08:09:06

标签: php

在我开始详细解释之前,让我展示一下我想要的结果截图。

enter image description here

我想要实现的非常简单,显示添加到购物车的所有项目并计算每个产品的总数。但是,看起来我的多维数组和array_key_exists没有正确地做到这一点,这就是为什么没有得到我想要的结果。

正如您从屏幕截图中看到的那样,如果将相同的产品添加到购物车,则数量不会加1,而只会显示在上一个项目下方。

products.php - >没什么特别的,只是为了显示数据库中的所有产品

<?php 
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );

if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
    //echo "id: " . $row["id"]. " <br>- Name: " . $row["product_name"]. " " . $row["product_price"]. "";
     echo '<p>ID->'.$row['id'].' | '.$row['product_name'].' | $'.$row['product_price'].'
     | <a href="cart.php?id='.$row['id'].'">Add to Cart</a></p>';
}
}
?>

cart.php

<?php
session_start();

if(isset($_GET['id'])){

require 'config.php';
$id=$_GET['id'];
$q = mysqli_query( $db->conn(), "SELECT * FROM product where id='$id'" );
$row = mysqli_fetch_assoc($q);
$product_name=$row['product_name'];
$product_price=$row['product_price'];
$quantity=1;
$total=$quantity*$product_price;

if(!isset($_SESSION['cart'])){
    $_SESSION['cart'][]=[]; //Create session 1st time
}   
if(isset($_SESSION['cart'])){

    if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];

    }else {
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
    }

    echo '<table border="1" cellpadding="10">'; 
    echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
    foreach ($_SESSION['cart'] as $key => $row) { // list out all the items in Multi array
        echo "<tr>";
        foreach ($row as $key2 => $val) {
        echo "<th>";
        echo $_SESSION['cart'][$key][$key2]." ";
        echo "</th>";
        }
    echo "</tr>";
    }
    echo '</table>';

}
}
?>

我可以知道哪部分编码出错了吗?

2 个答案:

答案 0 :(得分:2)

添加购物车和更新购物车

时,您犯了错误

因此请更改以下行

if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
} 

<强>向

$find = false;
if(!empty($_SESSION['cart'])){
    foreach($_SESSION['cart'] as $key=>$cart){
        if(isset($cart[0]) && $cart[0] == $id){ //Already exists in Cart
            $_SESSION['cart'][$key][3] = $_SESSION['cart'][$key][3] + 1; //$_SESSION['cart'][$key][3] is quantity 
            $_SESSION['cart'][$key][4] = $_SESSION['cart'][$key][3] * $_SESSION['cart'][$key][2] ; //$_SESSION['cart'][$key][4] update the total
            $find = true;
        }
    }
}
if(!$find){ //Not in the Cart
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}

注意:在检查之前,请清除Cookie

答案 1 :(得分:2)

cart.php文件中重新访问代码在这里会有很大的好处。以下是您可能要考虑的事项:

<?php
    $product_name   = $row['product_name'];
    $product_price  = $row['product_price'];
    $quantity       = 1;
    $total          = $quantity*$product_price;

    if(!isset($_SESSION['cart'])){
        $_SESSION['cart']           = [];
    }

    if(isset($_SESSION['cart'])){
        // DOES THE PRODUCT ID EXIST IN THE $_SESSION['cart'] COLLECTION?
        // IF IT DOESN'T WE CREATE IT AND LET IT BE...
        if(!array_key_exists( $id, $_SESSION['cart'] )){
            $_SESSION['cart'][$id]  = [$id, $product_name, $product_price, $quantity, $total];
        }else {
            // IF IT ALREADY EXIST; WE SIMPLY GET THE OLD VALUES & APPEND NEW ONE TO IT...

            // HERE YOU ASKED FOR array_key_exits($id, $_SESSION['cart']);
            // WHICH MEANS $id MUST BE THE KEY HERE
            // HERE IS WHERE THE PROBLEM IS....
            $storedPrice            = $_SESSION['cart'][$id][2];
            $storedQuantity         = $_SESSION['cart'][$id][3];
            $storedTotal            = $_SESSION['cart'][$id][4];
            $_SESSION['cart'][$id]  = [
                                        $id,
                                        $product_name,
                                        $product_price,
                                        $storedQuantity+1,
                                        round( ($storedQuantity+1)*($product_price), 2),
                                    ];
        }

        echo '<table border="1" cellpadding="10">';
        echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';


        foreach ($_SESSION['cart'] as $key => $row) {
            echo        "<tr>";
            foreach ($row as $key2 => $val) {
                echo    "<th>";
                echo    $_SESSION['cart'][$key][$key2]." ";
                echo    "</th>";
            }
            echo        "</tr>";
        }
        echo '</table>';

    }