I'm developing a cart and I need to get a subtotal of items added to cart. How to do that when variable is outside of foreach loop ? At first I'm looping every product like this:
我正在开发一个购物车,我需要将一个项目小计添加到购物车中。当变量超出foreach循环时如何做到这一点?起初我正在循环每个产品:
@foreach($products as $p)
{{$p['title']}}
{{$p['price']}}
@endforeach
And then how do I need to get the subtotal of all products price outside this loop ?
那么我如何才能在此循环之外获得所有产品的小计价格?
1 个解决方案
#1
1
There's not a clean solution for this if you want to achieve this in view however you can still use this code inside your view
template as well.
如果你想在视图中实现这一点,那么对于这个没有一个干净的解决方案,但你仍然可以在视图模板中使用此代码。
You can pass the subtotal
value explicitly from your controller method and display it in view. It could have been done like this. Add this code inside your controller function.
您可以从控制器方法显式传递小计值并在视图中显示它。它可以这样做。在控制器功能中添加此代码。
//initialize an empty array
$subtotal = [];
foreach($products as $p){
$price = $p['price'];
$title = $p['title'];
//push the price item to your subtotal array
array_push($subtotal, $price);
}
now you can use array_sum()
to get the subtotal of your product like
现在您可以使用array_sum()来获取产品的小计
$finalTotal = array_sum($subtotal); //returns sum of an array
now i hope you are passing products
from inside your controller. You just need to pass $finalTotal
now. For example
现在我希望你从控制器内传递产品。你现在只需要传递$ finalTotal。例如
return view('yourview')->with(array(
'products' => $products,
'finalTotal' => $finalTotal
));
Now in your blade template you can access subtotal
by just doing {{$finalTotal}}
. I hope you get it
现在,在您的刀片模板中,您只需执行{{$ finalTotal}}即可访问小计。我希望你明白
You can embed this code in order to get total in view. I hope this will help you
您可以嵌入此代码以获得全部视图。我希望这能帮到您
#1
1
There's not a clean solution for this if you want to achieve this in view however you can still use this code inside your view
template as well.
如果你想在视图中实现这一点,那么对于这个没有一个干净的解决方案,但你仍然可以在视图模板中使用此代码。
You can pass the subtotal
value explicitly from your controller method and display it in view. It could have been done like this. Add this code inside your controller function.
您可以从控制器方法显式传递小计值并在视图中显示它。它可以这样做。在控制器功能中添加此代码。
//initialize an empty array
$subtotal = [];
foreach($products as $p){
$price = $p['price'];
$title = $p['title'];
//push the price item to your subtotal array
array_push($subtotal, $price);
}
now you can use array_sum()
to get the subtotal of your product like
现在您可以使用array_sum()来获取产品的小计
$finalTotal = array_sum($subtotal); //returns sum of an array
now i hope you are passing products
from inside your controller. You just need to pass $finalTotal
now. For example
现在我希望你从控制器内传递产品。你现在只需要传递$ finalTotal。例如
return view('yourview')->with(array(
'products' => $products,
'finalTotal' => $finalTotal
));
Now in your blade template you can access subtotal
by just doing {{$finalTotal}}
. I hope you get it
现在,在您的刀片模板中,您只需执行{{$ finalTotal}}即可访问小计。我希望你明白
You can embed this code in order to get total in view. I hope this will help you
您可以嵌入此代码以获得全部视图。我希望这能帮到您