根据嵌套数组中的值删除数组元素

Delete an array element based on value from nested array

我已尝试使用 PHP unset(key) 函数根据其中的嵌套数组中的值删除整个父数组。

嵌套数组看起来像

Array ( 
[0] => Array ( 
    [ID] => 9909 
    [SHIPPING_AMOUNT] => 5 
    [TOTAL_TAX] => 0 
    [GRAND_AMOUNT] => 49.97 
    [ITEMS_AMOUNT] => 44.97 
    [ITEMS] => Array ( 
        [0] => Array ( 
            [CODE] => TEST
            [QTY] => 1 
            [UNIT_PRICE] => 14.99 ) 
        [1] => Array ( 
            [CODE] => NNKIT 
            [QTY] => 1 
            [UNIT_PRICE] => 9.99 ) 
        [2] => Array ( 
            [CODE] => MAINKIT 
            [QTY] => 1 
            [UNIT_PRICE] => 19.99 )
        ) 
    ) 
[1] => Array ( 
    [ID] => 9910 
    [SHIPPING_AMOUNT] => 5 
    [TOTAL_TAX] => 0 
    [GRAND_AMOUNT] => 74.96 
    [ITEMS_AMOUNT] => 69.96 
    [ITEMS] => Array ( 
        [0] => Array ( 
            [CODE] => NNKIT 
            [QTY] => 1 
            [UNIT_PRICE] => 9.99 ) 
        [1] => Array ( 
            [CODE] => MAINKIT 
            [QTY] => 3 
            [UNIT_PRICE] => 19.99 ) 
        ) 
    ) 
[2] => Array ( 
    [ID] => 9911 
    [SHIPPING_AMOUNT] => 5 
    [TOTAL_TAX] => 0 
    [GRAND_AMOUNT] => 44.98 
    [ITEMS_AMOUNT] => 39.98 
    [ITEMS] => Array ( 
        [0] => Array ( 
            [CODE] => MAINKIT 
            [QTY] => 2 
            [UNIT_PRICE] => 19.99 ) 
        ) 
    ) 
[3] => Array ( 
    [ID] => 9912 
    [SHIPPING_AMOUNT] => 5 
    [TOTAL_TAX] => 0 
    [GRAND_AMOUNT] => 29.98 
    [ITEMS_AMOUNT] => 24.98 
    [ITEMS] => Array ( 
        [0] => Array ( 
            [CODE] => TEST
            [QTY] => 1 
            [UNIT_PRICE] => 14.99 ) 
        [1] => Array ( 
            [CODE] => NEWTEST
            [QTY] => 1 
            [UNIT_PRICE] => 9.99 )
        )
    ) 

我检查的值是 CODE = MAINKIT。如果嵌套数组中不存在,则应删除主数组(在本例中为父数组 array[3])但不知何故返回的 key 来自嵌套数组而不是父数组。

PHP代码:

foreach($array as $key => $value){
    if(is_array($value) && $value['CODE'] != 'MAINKIT')
          unset($key);
}

CODE 元素在 $value['ITEMS'] 数组中,而不是直接在 $value 中。

要判断 MAINKIT 是否不在任何项目中,您必须遍历所有项目,测试它们是否匹配。如果 none 做,则删除数组元素。

尝试:

foreach($array as $key => $value){
    if (is_array($value) && is_array($value['ITEMS']))
        $found_mainkit = false;
        foreach ($value['ITEMS'] as $item) {
            if($item['CODE'] == 'MAINKIT') {
                $found_mainkit = true;
                break;
            }
        }
        if (!$found_mainkit) {
            unset($array[$key]);
        }
    }
}