尝试类似:
<?php
//Your cart array
$booksInCart = Array (
Array ('bookId' => 344, 'quantity' => 1),
Array ('bookId' => 54, 'quantity' => 1),
Array ('bookId' => 172, 'quantity' => 2),
Array ('bookId' => 3, 'quantity' => 1)
);
//User function to rebuild the array leaving out the bookID you want removed
function delete_book_from_cart($bookID, $haystack){
$ret = array();
foreach($haystack as $key=>$item){
if($item['bookId'] == $bookID) continue;
$ret[$key]=$item;
}
return $ret;
}
//Use like so
$booksInCart = delete_book_from_cart(172, $booksInCart);
/* Result
Array
(
[0] => Array
(
[bookId] => 344
[quantity] => 1
)
[1] => Array
(
[bookId] => 54
[quantity] => 1
)
[3] => Array
(
[bookId] => 3
[quantity] => 1
)
)
*/
print_r($booksInCart);
?>
可以使用相同的方法来更新一本书的数量:
//User function to rebuild the array updating the qty you want changed
function update_book_in_cart($bookID, $qty, $haystack){
$ret = array();
foreach($haystack as $key=>$item){
if($item['bookId'] == $bookID) $item['quantity'] = $qty;
$ret[$key]=$item;
}
return $ret;
}
等等