正如@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
是否有你使用'array_key_exists'而不是'isset($ item [$ add_to_cart])''的原因? –
製作產品ID數組的鑰匙要快得多:-) –
@HighwayofLife不是真的。 isset()'有更好的性能嗎? – Matt