2016-10-30 25 views
0

在下面的代碼我得到的輸出打印時它爆炸

Array ([0] => 1 [1] => 2)

但預期輸出數組是

Array ([0] => 1 [1] => 2 [2] => 3) Array ([0] => 1 [1] => 2) 

爲什麼總是執行第二如果條件?儘管第一個條件也是如此。 這是我試圖

<?php 
$test_arr=array(); 
$temp_option_arr=array(); 
$option_arr=array(); 

$options_array_val = Array (0 => "animals:1", 1 => "animals:2", 2 => "animals:3", 3 => "birds:1", 4 => "birds:2"); 

    foreach($options_array_val as $options_val) 
    { 
     $search_filter = explode(":", $options_val); 
     print_r($search_filter); 
     if(!in_array($search_filter[0],$option_arr)) 
     { 
      array_push($temp_option_arr,$search_filter[1]); 
      array_push($option_arr,$search_filter[0]); 
      $temp_option_arr=array(); 

     } 
     array_push($temp_option_arr,$search_filter[1]); 
    } 
    $test_arr[$search_filter[0]]=$temp_option_arr; 
    $find_species = array(); 
    if(!empty($test_arr['animals'])) 
    { 

     $find_species = $test_arr['animals']; 
     print_r($find_species); 

    } 

    if(!empty($test_arr['birds'])) 
    { 

     $find_species = $test_arr['birds']; 
     print_r($find_species); 
    } 

?>  
+1

你爲什麼'$ test_arr [$ search_filter [0] = $ temp_option_arr;''後foreach'結束? –

+1

你在代碼的第一部分清除了'$ temp_option_arr',所以它沒有任何關於「動物」的東西。當你退出第一個循環時。也許你應該說出你正在努力達到的目標,因爲這可以通過5行代碼解決方案來完成。 – trincot

回答

0

$test_arr[$search_filter[0]]=$temp_option_arr; 

是出在foreach範圍的代碼,因此它只會爲鳥類而不是動物的數組,所以你需要將其移動一行上部。

此外,分配temp_option_arr的值

array_push($temp_option_arr,$search_filter[1]); 

然後將其設置回空數組不使用它

$temp_option_arr=array(); 

您可以刪除第一個我想

0

你清楚$temp_option_arr在你的代碼的第一部分,所以它會有什麼,涉及動物的時候佑電子xit第一個循環。

但是,而不是使用所有的這些不同的陣列,只建立由物種控制的關聯陣列(動物,鳥類,...),並與作爲值的ID(1,2,3的陣列,...即:後的部分):

foreach($options_array_val as $options_val) { 
    list($species, $id) = explode(":", $options_val); 
    $option_arr[$species][] = $id; 
} 

這個循環$option_arr結構經過是這樣:

Array (
    "animals" => Array (1, 2, 3) 
    "birds" => Array (1, 2) 
) 

我認爲你可以做你想要什麼。例如只能獲得動物:

$option_arr["animals"] 

是:

Array (1, 2, 3)