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

标签 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>';

}
}
?>

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

最佳答案

重新访问 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>';

    }

关于PHP 多维数组 + array_key_exists 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969678/

相关文章:

javascript - Jquery Autocomplete 在本地主机上工作,但在远程服务器上给我解析错误

php - 流畅的接口(interface)和类的复杂性

php - 从 Dropbox Directory 拉取和显示网站图库中的图像

php - Sugarcrm,在保存记录的同时编写自定义代码

php - 在 PHP 脚本上运行 Cron 作业,在 Windows 的本地主机上

php - Symfony2 - 学说 :schema:update fails with entity outside of a bundle ( decoupled )

Ubuntu 的 PHP 编辑器

php - UPDATE 函数,用户 ID 未知

php - 如何为数据库中的列插入新名称

php - mysql中如何丢弃重复记录的插入?