2016-08-08 6 views
2

オブジェクトを持つ配列からアイテムを削除する際に問題があります。同じコードが他のアプリケーションで実行されています。ループした後に配列$categoriesは空でなければなりません。コードでは、すべての子カテゴリを削除して、親が子を持たずに削除する場合に、2番目のパラメータをTRUEとして渡すと親カテゴリを削除します。私たちは、アレイunset($children[$key]);のその特定のインデックス渡す必要がヌル配列要素の設定/除去するためオブジェクトの配列内でアンセットされたオブジェクト

//the $id of the category to be removed 
// $remove_children is state if you accept removing children categories 
function remove_category($id = null, $remove_children = false) { 
    if ($this->MD->is_category($id) && is_bool($remove_children)) { 
     //get all children category 
     $children = $this->get_children_categories($id); 
     if (!$children) { 
      return $this->MD->remove($id, $this->categories_table); 
     } else { 
      if ($remove_children && is_array($children)) { 
       unset($children['parent_category']); 
       foreach ($children as $child) { 
        $removed = $this->MD->remove($child->id, $this->categories_table); 
        if ($removed) { 
         //problem here 
         unset($child); 
        } 
       } 
       //the $children is not empty after remove all the items 
       if (empty($children)) { 
        return $this->MD->remove($id, $this->categories_table); 
       } else { 
        return false; 
       } 
      } else { 
       return false; 
      } 
     } 
    } else { 
     return false; 
    } 
} 

答えて

0

-

foreach ($children as $key=>$child) { 
        $removed = $this->MD->remove($child->id, $this->categories_table); 
        if ($removed) { 
         //problem here 
         unset($children[$key]); 
        } 
       } 

が、これはあなたを助けることを願っています。

+0

unset関数は、オブジェクト、変数、および配列で機能します。インデックスにはまったく依存しません。私はあなたのコードをテストすることを確認し、それは期待どおりのエラーで終了します。 $試してくれてありがとう。 phpリファレンスhttp://php.net/manual/en/function.unset.php –

+0

ああ申し訳ありませんが、あなたはunset($ children [$ key]);を書く必要があります。 –

+0

特定の配列要素を設定解除する配列の場合、設定を解除する特定の値索引を渡す必要があります。 –

関連する問題