正如@Matt 所说,您可能会重组您的购物车阵列。但是,如果您真的想使用当前的购物车结构:
$cart = array();
function add_item($cart, $item_id)
{
if(is_array($cart))
{
$added = false;
for($i=0; $i<count($cart); $i++)
{
if($cart[$i]['id'] == $item_id)
{
$cart[$i]['qty'] ++;
$added = true;
break;
}
}
if($added == false)
{
$i = count($cart);
$cart[$i]['id'] = $item_id;
$cart[$i]['qty'] = 1;
}
}
return $cart;
}
$cart = add_item($cart, 50);
$cart = add_item($cart, 50);
$cart = add_item($cart, 50);
$cart = add_item($cart, 25);
$cart = add_item($cart, 25);
$cart = add_item($cart, 10);
var_dump($cart);
它打印:
array
0 =>
array
'id' => int 50
'qty' => int 3
1 =>
array
'id' => int 25
'qty' => int 2
2 =>
array
'id' => int 10
'qty' => int 1
编辑:结构更好
$cart = array();
function add_item($cart, $item_id)
{
if(is_array($cart))
{
if(array_key_exists($item_id, $cart))
{
$cart[$item_id]++;
}
else
{
$cart[$item_id] = 1;
}
}
return $cart;
}
$cart = add_item($cart, 50);
$cart = add_item($cart, 50);
$cart = add_item($cart, 50);
$cart = add_item($cart, 25);
$cart = add_item($cart, 25);
$cart = add_item($cart, 10);
var_dump($cart);
它打印:
array
50 => int 3
25 => int 2
10 => int 1