2017-01-28 8 views
0

私はいくつかの場所をループしており、再帰関数を呼び出してこれらの場所のカテゴリとサブカテゴリを取得しています。 この関数は、以前のループ結果の組み合わせとしてデータを返しています。どのように私はこれを取り除くことができます、この私のコードはこのように見える私を助けてください。foreachループ内のPHP再帰関数が次のループ内の前のデータを追加しています

foreach ($data as $row) { 
    $get_options = categoryWithSubcategories(0, 0,$row['location_id'],$dbConn); 
    // here I am passing $row['location_id'] to this function, but it merge prvious data within next loop. 
} 

再帰関数は以下のとおりです。関数categoryWithSubcategoriesで

function categoryWithSubcategories($current_cat_id, $count,$locationId,$dbConn) 
{ 
    static $option_results; 
    // if there is no current category id set, start off at the top level (zero) 
    if (!isset($current_cat_id)) { 
     $current_cat_id =0; 
    } 
    // increment the counter by 1 
    $count = $count+1; 
    // query the database for the sub-categories of whatever the parent category is 
    $sql = "SELECT cat_id, cat_name from tbl_category where cat_parent_id = $current_cat_id and locationid=$locationId and delete_flag='0'"; 
    $stmt = $dbConn->prepare($sql); 
    $result =$stmt->execute(); 
    $data = $stmt->fetchAll(); 
    $num_options = $stmt->rowCount(); 
    if ($num_options > 0) { 
     foreach ($data as $categoryList) { 
      // if its not a top-level category, indent it to 
      //show that its a child category 
      if ($current_cat_id!=0) { 
       $indent_flag = ' '; 
       for ($x=2; $x<=$count; $x++) { 
        $indent_flag .= ' >> '; 
       } 
      } 
      $cat_name = $indent_flag.$categoryList['cat_name']; 
      $option_results[$categoryList['cat_id']] = $cat_name; 
      // now call the function again, to recurse through the child categories 
      categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn); 
     } 
    } 
    return $option_results; 
} 
+0

のように書くことができますか? – atoms

+0

あなたはreturnステートメントを見逃していませんか? 'return categoryWithSubcategories($ categoryList ['cat_id']、$ count、$ locationId、$ dbConn);' foreach-loop内 – Sepultura

答えて

1

() あなたはstaticとして$ option_resultsを定義しています。これは、関数が新しい各反復でマージ/追加された結果の背後にある理由です。

これを試すことができます: 1. $ option_resultsから静的を削除します。 2. function categoryWithSubcategories() の結果を下の行に格納します。

categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn); 

この

はあなたが必要なすべての情報を取得するためのSQLを変更することについて考えている

$option_results = array_merge(categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn), $option_results) ; 
+0

あなたは正しいです、ちょうど静的変数に気付きました。しかし、あなたから与えられた解決策は機能していません。しかし、私はこの静的変数の周りで遊ばなければならないという考えを持っています。 –

+0

なぜ動作していないのかを明確にしてください。期待した結果が得られていないか、何らかのエラーが発生していますか? –

+0

警告を投げていますarray_merge()最初の値は配列ではありません。 –

関連する問題