【发布时间】:2022-01-20 19:45:17
【问题描述】:
我的代码没有按照我将产品放入购物车会话的顺序打印产品。产品编号如下:
苹果价值 2
黑莓价值 3
绿葡萄价值6
正如您在打印的数组中看到的那样,我将它们放入购物车会话的顺序是葡萄、黑莓和苹果,但由于某种原因,它按给定值的顺序而不是购物车顺序打印。
不过,代码仍会将每个产品视为位于正确位置的产品。例如,假设苹果是购物车数组中葡萄当前所在的第三个项目。如果葡萄的数量按钮改变了,苹果的数量就会改变,因为它仍在正确读取数组。
我怀疑问题出在其中一个循环中,但我似乎找不到它是什么。
<?php
$total = 0;
$id_count = 0;
if(isset($_SESSION['cart']) and count($_SESSION['cart']) > 0){
$product_ID = array_column($_SESSION['cart'],"product_ID");
$result = $database->getData();
while($row = mysqli_fetch_assoc($result)){
foreach($product_ID as $id){
if($row['id']==$id){
print_r($product_ID);
print_r($row['product_name:']);
echo " value: $id";
$itemQuantity = $_SESSION['cart'][$id_count]['quantity'];
cartMethod($row['product_name'],$row['product_img'],$row['product_price'], $row['id'], $itemQuantity);
$total = $total + ($itemQuantity*(float)$row['product_price']);
$id_count++;
}
}
}
}
else{
echo "<h5>Cart is currently empty</h5>";
}
?>
这是位于不同文件中的 getData() 函数。
//get method to retrieve database information
public function getData(){
$sql = "SELECT * FROM $this->tablename";
$result = mysqli_query($this->connection, $sql);
if(mysqli_num_rows($result)>0){
return $result;
}
}
【问题讨论】:
-
"SELECT * FROM $this->tablename"没有ORDER BY子句。产品订单信息应该从哪里获得? -
关于产品订单的信息应该来自
$product_ID= array_column($_SESSION['cart'],"product_ID");print_r($product_ID)展示了项目的实际订单应该是什么。foreach循环将$product_ID的每个项目放入$id,然后将其与$row['id']进行比较。$product_ID中的第一项是 id 值为 6 的 Grapes,但if()似乎首先比较 Apples 的 id。
标签: php arrays session foreach e-commerce