【发布时间】:2016-09-25 15:16:15
【问题描述】:
我正在处理一个 laravel 购物网站项目,但我对购物车中产品的数量有疑问。 我对 Laravel 比较陌生,所以事情对我来说变得更加复杂...... 问题是我不能真正以有效的方式循环(并寻找)类似的产品。
但是当我按下“加入购物车”按钮时,这个功能就会运行:
public function cart(Product $product){
$cart = session()->get('cart');
// If Cart is empty, add a new array in the session
if ($cart == []) {
$cart[] = $product;
session()->put('cart', $cart);
}else{
// else if not empty, loop the cart and look if similar product is in the cart.
for ($i = 0; $i <= count($cart); $i++) {
$array_cart = json_decode($cart[$i], true);
if ($product->id == $array_cart["id"]) {
$array_cart["id"] += 1;
}else{
$cart[] = $product;
session()->put('cart', $cart);
}
}
}
return back();
}
产品是对象,我不确定如何循环查找产品的 id 以匹配数组产品 id。我尝试了 json_decode() 来查看它是否会使其成为一个数组,但我在这里可能是错的,因为当我返回值时它是同一个“对象”。例如,购物车中的单个产品可能如下所示:
[{"id": 4,
"name": "HP Desktop",
"description": "Ordinary desktop",
"category": "Desktop",
"price": 1,
"views": 63,
"created_at": "2016-04-11 14:42:58",
"updated_at": "2016-05-27 09:12:59"
}]
【问题讨论】:
标签: php laravel shopping-cart