0

我有相当简单的二维数组。我正在尝试编写一个函数来查找一个值是否存在于一个内部数组中。这并不难。问题是我需要在找到后删除整个内部数组。这就是我遇到的麻烦。似乎不可能使用 foreach 循环。

无论如何,这是数组。谢谢!

$booksInCart = Array (Array ('bookId' => 344, 'quantity' => 1), 
             Array ('bookId' => 54, 'quantity' => 1), 
             Array ('bookId' => 172, 'quantity' => 2), 
              Array ('bookId' => 3, 'quantity' => 1)
);
4

4 回答 4

1
// assume you want to delete bookId with 54.
$bookId = 54;
$booksInCart = array_filter($booksInCart, function ($var) use ($bookId) {
  return $var['bookId'] !== $bookId;
});
于 2013-09-04T02:48:11.487 回答
1

使用foreach带有键和值的循环。使用unset()子数组的键...

foreach ($booksInCart as $key => $sub) {
    if ($sub['bookId'] == 172) {
        unset($booksInCart[$key]);
    }
}
于 2013-09-04T02:50:02.690 回答
1

尝试类似:

<?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;
}

等等

于 2013-09-04T02:57:44.480 回答
0

您可以做的是将内部数组的索引也存储在循环中,然后如果找到该值,则使用该索引从外部数组中删除它。就像是:

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));
        }
    }
}
于 2013-09-04T02:48:22.140 回答