Could you explain to me how the ones array
in my cart work, why it takes several array
different types to add products to the shopping cart.
I have searched the documentation on PHP, I have managed to understand with the examples shown, but I would understand much better a short explanation taking my code as an example :)
<?php
session_start();
include('db.php');
$status="";
if (isset($_POST['code']) && $_POST['code']!=""){
$code = $_POST['code'];
$result = mysqli_query($con,"SELECT * FROM `products` WHERE `code`='$code'");
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
$code = $row['code'];
$price = $row['price'];
$image = $row['image'];
$cartArray = array(
$code=>array(
'name'=>$name,
'code'=>$code,
'price'=>$price,
'quantity'=>1,
'image'=>$image
)
);
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
$status = "<div class='box'>¡El producto se agrego al carrito!</div>";
} else {
$array_keys = array_keys($_SESSION["shopping_cart"]);
if(in_array($code,$array_keys)) {
$status = "<div class='box' style='color:red;'>¡El producto ya está añadido a su carrito!</div>";
} else {
$_SESSION["shopping_cart"] = array_merge($_SESSION["shopping_cart"],$cartArray);
$status = "<div class='box'>¡El producto se agrego al carrito!</div>";
}
}
}
?>
The following corresponds to an ASSOCIATIVE ARRAY
Los arrays asociativos son arrays cuyos keys son strings personalizados. Para acceder a los valores de un array asociativo se hace de la misma forma que con arrays numéricos, mediante corchetes
So in your code you have an array of name
cartArray
that contains an associative array with the value of$code
, which in turn has another associative array with the values returned by the database query.