1

我尝试使用 PHPunset(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);
}
4

1 回答 1

3

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]);
        }
    }
}
于 2016-01-21T18:02:33.240 回答