2016-01-21 153 views
1

我嘗試使用基於來自嵌套數組的值的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); 
} 

回答

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

貌似是做與我相似,只是一步 - 刪除嵌套的'ITEMS'排列不整父陣列 – JackTheKnife

+1

它刪除'$陣列[$關鍵]',而不是' $ item'。 – Barmar

+0

我看到問題了,給我一下。 – Barmar