2016-08-16 1 views
2

Avant de commencer à expliquer dans les détails, laissez-moi montrer la capture d'écran de ce que je veux que le résultat soit.PHP Multidimensional Arrays + array_key_exists ne fonctionne pas correctement

enter image description here

Ce que je veux obtenir est assez simple, afficher tous les éléments qui sont ajoutés au panier et calculer le total pour chaque produit. Cependant, ressemble à mes tableaux multidimensionnels et array_key_exists ne l'a pas fait correctement et c'est pourquoi n'a pas obtenu le résultat que je veux.

Comme vous pouvez le voir sur la capture d'écran, si le même produit est ajouté au panier, la quantité n'a pas plus 1 et elle s'affiche juste en dessous de l'article précédent.

products.php -> rien de spécial, juste pour afficher tous les produits de base de données

<?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>'; 

} 
} 
?> 

Puis-je savoir quelle partie du codage est allé faux?

+0

Pourquoi ne pas laisser le moteur SQL faire cela? Comme 'SELECT Nom, AVG (Prix), SUM (Quantité), (Prix * Quantité) comme Total FROM product GROUP BY Name' – Bobot

Répondre

2

Revisiter le code dans votre fichier cart.php serait d'un grand avantage ici. Voici ce que vous pouvez envisager:

<?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>'; 

    } 
2

Vous avez fait l'erreur, quand ajouter un panier et mise à jour panier:

changer donc la ligne suivante:

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]; 
} 

Dans

$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]; 
} 

Note: Avant de cocher, effacez les cookies

+0

votre codage ne fonctionne pas :(la quantité n'a pas été ajoutée correctement et le même article affichera ci-dessous un autre – gosulove

+1

Avant le contrôle s'il vous plaît effacer les cookies –