在PHP中查找是否存在内部数组的值,如果找到,则删除该数组

时间:2013-09-04 02:43:52

标签: php arrays

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

无论如何,这是阵列。谢谢!

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

4 个答案:

答案 0 :(得分:1)

// assume you want to delete bookId with 54.
$bookId = 54;
$booksInCart = array_filter($booksInCart, function ($var) use ($bookId) {
  return $var['bookId'] !== $bookId;
});

答案 1 :(得分:1)

使用带有键和值的foreach循环。使用密钥unset()子阵列......

foreach ($booksInCart as $key => $sub) {
    if ($sub['bookId'] == 172) {
        unset($booksInCart[$key]);
    }
}

答案 2 :(得分: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;
}

等等

答案 3 :(得分: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));
        }
    }
}