在foreach循环期间从数组中删除项目

时间:2014-07-26 00:39:07

标签: php arrays foreach

我在PHP中执行了以下foreach

我想要做的是代替$invalid_ids[] = $product_id;构建,然后循环,我会反而希望从循环的数组中删除条目,因为我在它周围循环。

例如:

如果当前$product_id未通过任何测试,请从$current_list数组中删除该项,然后继续foreach循环的下一次迭代。

我尝试unset($product_id)foreach循环标题如下所示:foreach ($current_list as &$product_id) {,但项目项仍在数组中。

有没有人对如何做到这一点有任何想法?

foreach ($current_list as $product_id) {
    // Test 1 - Is the product still active?
    // How to test? - Search for a product in the (only active) products table 

    $valid = $db->Execute("SELECT * FROM " . TABLE_PRODUCTS . " WHERE products_id = " . $product_id . " AND products_status = 1");
    // Our line to check if this is okay.

    if ($valid->RecordCount <= 0) { // We didn't find an active item.
        $invalid_ids[] = $product_id;
    }

    // Test 2 - Is the product sold out? 
    if ($valid->fields['products_quantity'] <= 0 and STOCK_ALLOW_CHECKOUT == "false") { // We found a sold out item and it is not okay to checkout.
        $invalid_ids[] = $product_id; 
    }

    // Test 3 - Does the product have an image?
    if (empty($valid->fields['products_image'])) { // Self explanatory.
        $invalid_ids[] = $product_id;
    }
}

2 个答案:

答案 0 :(得分:2)

$product_id不是数组中的实际数据,而是它的副本。您需要unset来自$current_list的项目。

我不知道$current_list是如何存储的,但unset($current_list['current_item']之类的东西可以解决问题。您可以使用key选择数组中的current_item键。

从PHP key文档中迭代数组的类似方法,您可以从中获取数组键...

while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}

未经测试,但是这样......

while ($product_id = current($current_list)) {

    // Do your checks on $product_id, and if it needs deleting...
    $keyToDelete = key($array);
    unset($current_list[$keyToDelete]);

    next($current_list);
}

答案 1 :(得分:1)

我认为这个简单的代码可以帮助你

让我们说我们有一个整数数组,我们想删除所有等于&#34; 2&#34;在foreach循环内部

$array = [1,2,1,2,1,2,1];
foreach ($array as $key => $value) 
{
   if($value==2)
      unset($array[$key]);
}
var_dump($array);

这显示以下结果

array (size=4)
  0 => int 1
  2 => int 1
  4 => int 1
  6 => int 1