【发布时间】:2021-12-31 20:32:45
【问题描述】:
我正在开发电子商务网站。而且我有以下购物车类,可以在购物车中推送或增加产品并做其他事情。
class cart{
public static function add($request)
{
try {
if(!isset($_SESSION['user_cart'][$request['product_id']]) || $_SESSION['user_cart'][$request['product_id']] < 1)
{
$_SESSION['user_cart'][$request['product_id']]
[$request['size_id']] = 1;
}
else {
if(!isset($_SESSION['user_cart'][$request['product_id']][$request['size_id']])){
$_SESSION['user_cart'][$request['product_id']]
[$request['size_id']] = 1;
} else {
$qty = $_SESSION['user_cart'][$request['product_id']][$request['size_id']];
$_SESSION['user_cart'][$request['product_id']]
[$request['size_id']] = $qty + 1;
}
}
}
catch (\Exception $ex){
echo $ex->getMessage();
}
}
public static function removeItem($index)
{
if(count(Session::get('user_cart')) <= 1){
self::clear();
}else{
unset($_SESSION['user_cart'][$index]);
sort($_SESSION['user_cart']);
}
}
public static function clear()
{
Session::remove('user_cart');
}}
并且我有以下控制器类来读取和获取用户购物车中的项目并使用“杰森”返回刀片。我的刀片正在工作,但我无法从下面的功能中获取购物车物品。
public function getCartItems()
{
try{
$result = array();
$cartTotal = 0;
if(!Session::has('user_cart') || count(Session::get('user_cart')) < 1){
echo json_encode(['fail' => "No item in the cart"]);
exit;
}
$index = 0;
foreach ($_SESSION['user_cart'] as $cart_items){
$productId = $cart_items['product_id'];
$quantity = $cart_items['quantity'];
// $size_id = $cart_items['size_id'];
if($cart_items['size_id'] == null){
$size_id = 1;
}else{
$size_id = $cart_items['size_id'];
}
$item = Product::where('id', $productId)->first();
$stock = Productattribute::where('product_id', $productId)->sum('quntity');
$size = Size::where('id', $size_id)->first();
if(!$item) { continue; }
// check if product is in hotsales or not
if($item->product_on == 1){
$price = $item->sales_price;
}else{
$price = $item->price;
}
$totalPrice = $price * $quantity;
$cartTotal = $totalPrice + $cartTotal;
$totalPrice = number_format($totalPrice, 2);
array_push($result, [
'id' => $item->id,
'title' => $item->title,
'image' => $item->product_image_path,
'price' => $price,
'total' => $totalPrice,
'quantity' => $quantity,
'stock' => $stock,
'size' => $size->name,
'index' => $index
]);
$index++;
}
$cartTotal = number_format($cartTotal, 2);
echo json_encode(['items' => $result, 'cartTotal' => $cartTotal]);
exit;
}catch (\Exception $ex){
echo $ex->getMessage() .' '.$ex->getLine();
//log this in database or email admin
}
}
}
我在这里做错了什么。有没有其他方法可以从我拥有的数组中读取值。 我从会话中获取以下数组。应该如何读取数据?在购物车控制器的 getcart 函数中。
Array
(
[4] => Array
(
[3] => 1
)
[5] => Array
(
[3] => 6
[4] => 1
)
[3] => Array
(
[3] => 1
)
[7] => Array
(
[4] => 1
[3] => 1
)
)
【问题讨论】:
-
你有会话数据吗?你检查了吗?
-
是的。我已经检查过了。
-
请显示getCartItems的dd结果dd($_SESSION['user_cart']);
-
在此之前我在该问题开始后获取数据。感谢您的宝贵时间
-
好吧,祝你好运,我怀疑会话没有设置。
标签: php laravel session session-variables