2011-11-10 54 views
3

我有一個數組像這樣後:PHP - 如何刪除數組的所有元素之一所指定

陣列([740073] => Leetee貓1 [720102] =>貓1 SUBCAT 1 [730106 ] => subsubcat [740107] =>和另一[730109] =>測試貓)

我想刪除與 '720102' 的一個關鍵元素後落入本數組的所有元素。因此,陣列將成爲:

陣列([740073] => Leetee貓1 [720102] =>貓1 SUBCAT 1)

我將如何實現這一目標?我只有belw那麼遠,

foreach ($category as $cat_id => $cat){ 
    if ($cat_id == $cat_parent_id){ 
    //remove this element in array and all elements that come after it 
    } 
} 

[編輯]第1回答似乎在大多數情況下,但不是所有的工作。如果原始數組中只有兩個項目,它只會刪除第一個元素,而不是後面的元素。如果只有兩個元素

陣列([740073] => Leetee貓1 [740102] =>貓1 SUBCAT 1)

變得

陣列([740073] => [740102] => cat 1 subcat 1)

這是爲什麼?這似乎是隻要$位置爲0

回答

7

就個人而言,我會用array_keysarray_searcharray_splice。通過使用array_keys來檢索密鑰列表,您將所有密鑰都作爲以0的密鑰開頭的數組中的值。然後,您使用array_search來查找將成爲原始數組中鍵的位置的鍵的鍵(如果這有意義的話)。最後,array_splice用於刪除位置之後的任何數組值。

PHP:

$categories = array(
    740073 => 'Leetee Cat 1', 
    720102 => 'cat 1 subcat 1', 
    730106 => 'subsubcat', 
    740107 => 'and another', 
    730109 => 'test cat' 
); 

// Find the position of the key you're looking for. 
$position = array_search(720102, array_keys($categories)); 

// If a position is found, splice the array. 
if ($position !== false) { 
    array_splice($categories, ($position + 1)); 
} 

var_dump($categories); 

輸出:

array(2) { 
    [0]=> 
    string(12) "Leetee Cat 1" 
    [1]=> 
    string(14) "cat 1 subcat 1" 
} 
+0

這似乎在大多數情況下工作,但不是全部。請參閱編輯原始郵件,其中顯示不起作用的示例。 – LeeTee

+0

好的,awnswer是正確的,但是如果$ position = 0就有問題。需要寫($ position!== FALSE)而不是if($ position)。謝謝 – LeeTee

+0

對不起。這很有道理。 ;)我會修復上面的答案。 –

-1

試試這個

$newcats = array(); 
foreach($category as $cat_id => $cat) 
{ 
    if($cat_id == $cat_parent_id) 
     break; 

    $newcats[$cat_id] = $cat; 
} 

$category = $newcats; 
+0

是的,我試過這種方式,因爲它似乎是個emost邏輯,但它不工作因某種原因.... – LeeTee

-1

有一對夫婦的方式來做到這一點,但使用當前的結構,你可以設置一個標誌,並刪除,如果標誌設置...

$delete = false; 
foreach($category as $cat_id => $cat){ 
    if($cat_id == $cat_parent_id || $delete){ 
     unset($category[$cat_id]); 
     $delete = true; 
    } 
} 
+0

這並不似乎工作 – LeeTee

相關問題