2016-03-29 58 views
2

如何從多維數組中取消所有名爲id的鍵?取消多維數組中的所有ID鍵

private function remove_id(Array &$arr){ 
    foreach($arr as $key => $value){ 
     if($key == 'id'){ 
      unset($arr[$key]); 
     } 
     elseif(is_array($value)){ 
      $this->remove_id($value); 
     } 
    } 
} 

陣列

Array 
(
    [id] => 52453 
    [periods] => Array 
     (
      [0] => Array 
       (
        [id] => 95296 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 1 
       ) 

      [1] => Array 
       (
        [id] => 95297 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 2 
       ) 

      [2] => Array 
       (
        [id] => 95298 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 3 
       ) 

      [3] => Array 
       (
        [id] => 95299 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 4 
       ) 

      [4] => Array 
       (
        [id] => 95300 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 5 
       ) 

      [5] => Array 
       (
        [id] => 95301 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 6 
       ) 

      [6] => Array 
       (
        [id] => 95302 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 7 
       ) 

      [7] => Array 
       (
        [id] => 95303 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 8 
       ) 

      [8] => Array 
       (
        [id] => 95304 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 9 
       ) 

      [9] => Array 
       (
        [id] => 95305 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 10 
       ) 

      [10] => Array 
       (
        [id] => 95306 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 11 
       ) 

      [11] => Array 
       (
        [id] => 95307 
        [is_readonly] => 0 
        [year] => 2016 
        [month] => 12 
       ) 

     ) 

    [closing_profit_amount] => 0 
    [closing_profit_net_amount] => 0 
) 
+0

唯一錯誤的事情,我可以看到的是,你正在修改你正在迭代的對象,這可能會導致意想不到的副作用。但是這會給你什麼錯誤,或者它不起作用? – valepu

+0

它沒有返回錯誤..但是數組沒有被修改 – clarkk

+0

我們可以看到數組嗎? – izk

回答

4

您需要使用&valuefor循環,以保持在嵌套數組的變化。

同樣的陣列不能有超過1 id關鍵,所以沒有必要循環,這讓有點microoptimization這裏內檢查:

private function remove_id(Array &$arr){ 
    if(isset($arr['id'])) { 
     unset($arr['id']); 
    } 
    foreach($arr as &$value){ 
     if(is_array($value)){ 
      $this->remove_id($value); 
     } 
    } 
}