我正在制作购物车系统,并且我的会话正在使用foreach()函数显示。在这个函数里面,我有一个名为$ item_price的变量。我希望将所有$ item_price加起来,这样我就可以得到总计。PHP将所有的值加起来foreach()
这怎么办?我不知道这个问题应该如何解决:/
这是我的foreach()代码:
foreach($session_cart as $cart_items) {
$fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'");
while($shop_items = mysql_fetch_array($fetch_info)) {
$item_id = $shop_items['item_id'];
$item_name = $shop_items['item_name'];
$item_quantity = count(array_keys($session_quantity, $item_id));
$item_price = $shop_items['item_price'] * $item_quantity; }
$cartOutput .= '<h2>'.$item_name.'</h2>';
$cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>';
$cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>';
$cartOutput .= '<a> ID: '.$item_id.'</a><br><br>';
}
发布您的代码,使我们可以帮助适当。 – 2014-10-27 19:01:22
它是一个不可见的'foreach()'函数吗? – 2014-10-27 19:02:21
如果通过“变量名为$ item_price”,你实际上是指数组键和值,那么['array_column'](http://php.net/array_column)+ ['array_sum'](http://php.net/ array_sum)就足够了。 – mario 2014-10-27 19:02:35