2014-07-26 115 views
1

我在PHP中执行了以下foreach在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; 
    } 
} 

回答

1

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

比方说,我们有一个整数数组,我们要删除foreach循环内所有等于“2”的项目

$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 
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); 
} 
+0

'$ current_list'也是在功能初建的数组。但我会尽力回答你的答案。 –