Reputation: 585
I have fairly simple 2 dimensional array. i'm trying to write a function that finds if a value exists in one of the inner arrays. that is not so hard. problem is that i need to then delete the entire inner array once found. that's what i'm having trouble with. seems impossible to do using foreach loops.
anyway, here is the array. thanks!
$booksInCart = Array (Array ('bookId' => 344, 'quantity' => 1),
Array ('bookId' => 54, 'quantity' => 1),
Array ('bookId' => 172, 'quantity' => 2),
Array ('bookId' => 3, 'quantity' => 1)
);
Upvotes: 0
Views: 773
Reputation: 46602
Try something like:
<?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);
?>
The same method can be used to update quantity's of a book:
//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;
}
and so on
Upvotes: 1
Reputation: 13283
Use the foreach
loop with key and value. Use the key to unset()
a sub-array...
foreach ($booksInCart as $key => $sub) {
if ($sub['bookId'] == 172) {
unset($booksInCart[$key]);
}
}
Upvotes: 1
Reputation: 3368
What you can do is store the index of the inner array in the loop as well, and then if the value is found delete it from the outer array using that index. Something like:
foreach ($booksInCart as $id => $inner) {
// Second foreach loop because you didn't specify which value you're checking
// and I want to insure complete thoroughness
foreach ($inner as $key => $value) {
if ($key == $requiredkey && $value == $requiredvalue) {
unset($booksInCart($id));
}
}
}
Upvotes: 0
Reputation: 160833
// assume you want to delete bookId with 54.
$bookId = 54;
$booksInCart = array_filter($booksInCart, function ($var) use ($bookId) {
return $var['bookId'] !== $bookId;
});
Upvotes: 1