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

时间:2016-01-21 17:56:05

标签: php arrays multidimensional-array array-unset

我尝试使用基于嵌套数组中的值的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。如果嵌套数组中不存在,则应删除主数组(在本例中为parent array[3])但以某种方式返回key来自嵌套数组而不是父数组。

PHP代码:

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

1 个答案:

答案 0 :(得分:2)

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

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

尝试:

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]);
        }
    }
}